Oct 092010
 

penguinsleepSuppose you have a long-running task (for example, compiling a large program) that you need to run, but you also want to get some other work done. Linux lets you start a task in the background and keep on doing other things from the command prompt.

We will see in this article how to send commands in the background, then return them to the foreground, and make sure that also closing the current shell or terminal the process doesn’t remains tied to the session but continue to work.

An alternative to these command is using screen, as read in a former article, but now let’s see the command bg and the special character &


Task 1 : start a process directly in background

sleep 100 &

This will start the sleep as a background task, executing it in parallel with other tasks on your system, the special character & after the command means that.

There is no output and you’ll be back at command prompt, after 100 seconds you’ll get

[1]+ Done sleep 100

Task 2 : start a process and put it in background

This is useful when you start something long, and realize you need your prompt back to give some other command.

sleep 100 ; < CTRL > Z ; bg

In this sequence we run a command (sleep, but could be anything), after that we use < ctrl > Z to put the process in Suspend State and we use the command bg to put the process in background

Example of output:

laptop:~$ sleep 100

^Z

[1]+ Stopped sleep 100

laptop:~$ bg

[1]+ sleep 100 &

laptop:~$

[1]+ Done sleep 100

Note: It’s a good idea to redirect the output of background tasks to a file, since the background task still shares the console with foreground tasks. If you don’t, the background task will splash any output it might produce all over your screen while you’re editing a file or typing another command.

Task 3 : Move a process from background to foreground

Usefull if we want to bring back on foreground a command we have sent in the bg.

sleep 100 &; sleep 100; < CTRL > Z ; bg ; jobs ; fg 2

In this sequence we put 2 process of sleep in background, after that we use the command jobs to have a list of all the processes in the background and fg 2 to bring in foreground the process number 2 .

Example of output:

laptop:~$ jobs

[1]- Running sleep 100 &

[2]+ Running sleep 100 &

Task 4 : Start a process, log off and have the process running

As a simple example, assume that you have a Linux command named myLongRunningJob.sh that you want to run, but you know if will take over three hours to run and you have to log off now, how can you do it ?

nohup myLongRunningJob.sh &

If standard input is a terminal, redirect it from /dev/null. If standard output is a terminal, append output to `nohup.out’ if possible, `$HOME/nohup.out’ otherwise. If standard error is a terminal, redirect it to standard output. To save output to FILE, use `nohup COMMAND > FILE'.

So we’ll find the output of our command in the file nohup.out.

Note:By itself, nohup does not run tasks in background, you must provide the character & at the end of the command line or use the CTRL-Z and put the tasks in background with the command bg.


Task 5 : Log off from a terminal keeping active a process we started without nohup

You have to log off from the terminal, but you are in the middle of that long task what to do ?

mylongtask.sh ; < ctrl > Z; bg; disown -h %1

After we put on background the process, disown it from the current terminal. The disown prevents a SIGHUP to the process if my terminal dies.

from the man page –

disown [-ar] [-h] [jobspec …]
Without options, each jobspec is removed from the table of active jobs. If the -h option is given, each jobspec is not removed from the table, but is marked so that SIGHUP is not sent to the job if the shell receives a SIGHUP. If no jobspec is present, and neither the -a nor the -r option is supplied, the current job is used. If no jobspec is supplied, the -a option means to remove or mark all jobs; the -r option without a jobspec argument restricts operation to running jobs. The return value is 0 unless a jobspec does not specify a valid job.

Of course, in the X Windows environment, all these unnatural gyrations are not necessary. Just start another shell window and run the other command there. You can watch both processes running in separate windows at the same time, and you don’t have to w orry about adding ampersands, piping output to files, or keeping track of foreground versus background processes.

Popular Posts:

Flattr this!

  12 Responses to “How to run commands in the background in Linux”

  1. Oh, never heard about $ disown before, i always use $ screen to keep processes running or run it on startup if it need a terminal like some kind of video players. Thank you.

  2. Use setsid instead of nohup.

  3. @ Lawrence: I’d never heard of setsid before. It looks to be perfect when one doesn’t care about STDIN/STDOUT, but needs to launch something from a script that should then terminate without affecting the launched program (as is often the case when launching an X based program).

    @ Linuxaria: After using &; disown for some time, I had been experimenting with nohup, but was having problems with it. Your comment that the & is still needed prompted me to discover why. (I had been using it, but after the redirect and apparently I needed it before the redirect.)

    Between the two tips, one in the OP one in the comments, this has just solved a serious frustration I’ve been working to solve on and off for months! =:^)

  4. Also the “at” command is an alternative to run things on the background.

  5. disown! nice tip, been wondering about that

    (very good for e.g. when you’ve started a huge sort without nohup/screen, and then find you have to log off from your ssh session)

  6. O attivato un processo con comando: mylongtask.sh ; Z; bg; disown -h %1 e funziona

    Una volta aperto il terminal come puoi fermare processo che lavora in background

  7. A me non funziona… se esco da terminale mi killa il processo….

    • Ciao, per uscire dal terminale e mantenere il processo attivo devi utilizzare nohup o disown (se il processo è già partito) cosa è che non ti funziona ?

      Io ho appena provato ad aprire un terminale e dare:

      mint-desktop ~ $ xterm
      ^Z
      [1]+ Stopped xterm
      mint-desktop ~ $
      mint-desktop ~ $
      mint-desktop ~ $ disown %1
      bash: warning: deleting stopped job 1 with process group 3232

      A questo punto chiudo il terminale e xterm mi rimane aperto.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

*