Background Processing

It is sometimes useful to get a command to run in the background, and return control to the shell immediately. If the script does not depend upon the results or status of the executed command, there is no need to wait for it to complete. The ampersand symbol (&) at the end of a command line does this. The PID of the backgrounded process is set in the variable $! and execution of the main script or interactive shell continues as normal. It can also monitor the activity of the backgrounded child process as it works. This dd command reads 512MB of random data from the /dev/urandom driver and writes it to a file named bigfile. The interactive shell lists bigfile as it grows, and uses the $! variable to monitor progress using ps and strace. The strace output shows the random data as it is being read from /dev/urandom and written to bigfile.

dd if=/dev/urandom of=bigfile bs=1024k count=512 &
[1] 3495
$ ls -lh bigfile
-rw-rw-r-- 1 steve steve 18M Jan 28 18:01 bigfile
$ ls -lh bigfile
-rw-rw-r-- 1 steve steve 196M Jan 28 18:02 bigfile
$ ps -fp $! UID        PID  PPID  C STIME TTY          TIME CMD steve     3495  3363 99 18:01 pts/1    00:00:44 dd if=/dev/urandom of=bigfile bs=10 24k count=512 $ strace -p $! 2>&1 | head -5 Process 3495 attached - interrupt to quit write(1, "\251\0\322\335J\362\214\334\331\342\213\356\377\23%\371\353U\377H\262\225 'w\r'_\316\306\220\325g"..., 828440) = 828440 read(0, "znm9;\311}\344\21z\342\"\215n\272d8\24\321\215\363\340\327%\213\3623&\273; ...

Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.