Tech Junkie Blog - Real World Tutorials, Happy Coding!: Linux Process Management: Running Processes In The Background And Foreground With bg And fg Command

Monday, March 21, 2022

Linux Process Management: Running Processes In The Background And Foreground With bg And fg Command

 Linux allows you to run jobs in the background and in the foreground.  It accomplish this by identifying the processes as jobs and assigning the state to the jobs by numbers.

First let's create a process, we are just create a sleep job in the background, with the command sleep 1500& the & automatically put the process in the background.  If you observe the behavior you will noticed that the prompt is in your control right away because it's running in the background.




If you run the jobs command you see the process is running but it's running in the background.  However if you forgot to put the & at the end the job will have to be finished before you get your prompt back, the only way to get your prompt back before then is to type CTRL+Z , but that would also stop the process or job from running.  That's probably not what you wanted




You've gotten your prompt back but you've also stopped the process, that's probably not what you wanted to do.  You want to get your prompt and keep the job running at the same time.  So the solution is to use the bg command to run the job in the background






To bring the job into the foreground you just type fg



As you can see you lose the prompt once the job is put in the foreground because it has to finish running the job before you can get the prompt back. Press CTRL+Z again to interrupt the process

Now there's another way to put a process in the background, that is to specify the job number.  So if we want to put the second job that was stopped in the background again we can type bg 2 







You can do the same thing with the fg command.  Kill the sleep process with the command pkill sleep for cleanup



2 comments:

  1. Wish to see much more like this. Thanks for sharing your information!
    https://www.infosectrain.com/courses/comptia-security-syo-601-training/

    ReplyDelete

Search This Blog