Running jobs in the foreground and background in Linux

Home > Search
  by

Let's use the PS command to view the processes running in our shell. Two processes are running, bash and the PS command.

[user1@server1 ]# ps
PID    TTY     TIME       CMD
15415  pts/0   00:00:00   bash
15435  pts/0   00:00:00   ps

 

Let's open a file in GEDIT and run it in the foreground. By note using the & symbol the job runs in the foreground. The file opens and the Terminal cannot be used.

[user1@server1 ]# gedit file1

 

If we open another Terminal, we can see that there is a PID for GEDIT.

[user1@server1 ]# ps -e | grep gedit
16020  pts/2   00:00:00   gedit

[user1@server1 ]# ps a | grep gedit
16020  pts/2   Sl+    0:00 gedit notes

 

There are a few ways to free up the Terminal that was used to start the GEDIT job in the foreground. One way is just to close GEDIT. Another option is to press Ctrl C or Ctrl Z in the Terminal that was used to start the GEDIT job. Ctrl C actually executes the kill command with the SIGINT signal. Another way is to use the kill command in the second Terminal to end the gedit process. In this example, GEDIT has PID 16020.

[user1@server1 ]# kill -9 16020

 

Running a job in the background solves this problem. Let's use the & symbol to run the job in the background. The file opens and we can still use Terminal. Terminal also shows the job ID and PID.

[user1@server1 ]# gedit file1 &

 

If we run the PS command again, we can see gedit in the list of active processes.

[user1@server1 ]# ps
PID    TTY     TIME       CMD
15415  pts/0   00:00:00   bash
15435  pts/0   00:00:00   ps
15449  pts/0   00:00:00   gedit

 

The JOBS command can be used to see the job ID of gedit.

[user1@server1 ]# jobs[1]+  Running  gedit file1 &

 

Let's open a few more instances of gedit.

[user1@server1 ]# gedit file2[2]  16105
[user1@server1 ]# gedit file3[3]  16115
[user1@server1 ]# gedit file4[4]  16117

 

Let's view the processes again.

[user1@server1 ]# ps
PID    TTY     TIME       CMD
15415  pts/0   00:00:00   bash
15435  pts/0   00:00:00   ps
16020  pts/0   00:00:00   gedit
16105  pts/0   00:00:00   gedit
16115  pts/0   00:00:00   gedit
16117  pts/0   00:00:00   gedit

 

Let's view the jobs again. The job with the + symbol is the most recently run job. The job with the - symbol are the second most recently run job.

[user1@server1 ]# jobs
[1]   Running  gedit file1 &
[2]   Running  gedit file2 &
[3]-  Running  gedit file3 &
[4]+  Running  gedit file4 &

 

We can move the job to the foreground using the FG command. Again, the Terminal cannot be used. We can close GEDIT, press Ctrl C, press Ctrl Z, or kill the process in another term to get our Terminal back.

[user1@server1 ]# fg %1

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments