Simple Process Management in Linux


When managing and maintaining a live Linux server, simple process management skills are indispensable. Each Linux server has scores of processes running at any one time, most of which are daemons (processes that have no parent and that generally exist in order to provide ongoing services). A minority of the running processes may be shell jobs, which are most often started from an interactive shell (command line). As an interactive shell user, you (or, rather, your shell) can carry out certain operations on these processes. This article shows one basic example of that – moving a process from the shell’s foreground to the background so that the shell can respond to further commands.



You have started a copy-operation to replicate a directory /mydir:

# cp -a /mydir /mnt/

The above command begins to replicate the existing directory as a sub-directory of /mnt.



However, if there is a lot of data to copy over, you may find that the command prompt has not returned for a while, whereas you need to get on with other things on this same server.



In this case, you should now put the cp job into the background:

Ctrl Z
[1]+  Stopped  cp -a /mydir /mnt/

Once you have pressed Ctrl Z, the shell stops (but does not terminate) the foreground process. The shell assigns a “job number” to the process (shown in square brackets), shows the command that began it, and returns the command prompt to you.
You then restart the job in the background with the following command:

# bg 1
[1]+  cp -a /backup /mnt/temp/ &

The shell shows the command with an ampersand appended to indicate that it is now running as a background process.  The shell prompt returns.

If you bring the job back into the foreground, the shell will display the job’s command followed by any standard output that it is producing (none in this case):

# fg 1
cp -a /mydir /mnt/

You may, from this point, put the job back into the background as described earlier, or terminate the job with Ctrl C:

If the job finishes in the background, your next command prompt will show a message that the job has finished:

[1] +   Done       cp -a /mydir /mnt/


Alternative Approach

You might, instead of starting the process in the foreground, start it in the background immediately, by adding an ampersand to the initial command:

# cp -a /mydir /mnt/ &
[1]    17579

In this case, the shell indicates the job number that it has assigned to the command and the process ID corresponding to the job.  Your command prompt returns immediately.  Later, when the job finishes in the background, the shell will inform you at the next available command prompt:

[1] +   Done       cp -a /mydir /mnt/


Final Remarks

We see that the Linux shell provides a very easy way to set processes going, put them into the background, and recall them to the foreground. Further articles will explore more ways that processes can be managed in Linux.