Checking and Managing Running Processes - Ubuntu Linux Toolbox: 1000+ Commands for Power Users (2013)

Ubuntu Linux Toolbox: 1000+ Commands for Power Users (2013)

Chapter 9

Checking and Managing Running Processes

IN THIS CHAPTER

· Viewing active processes with ps and top

· Searching for processes with pgrep

· Adjusting CPU priority with nice and renice

· Moving processes to the background or foreground

· Killing and signaling processes with kill and killall

· Using at and batch to run commands

· Scheduling commands to run repeatedly with cron

When an executable program starts up, it runs as a process that is under the management of your Linux system’s process table. Linux provides all the tools you need to view and change the processes running on your system.

The ps and top commands are great for viewing information on your running processes. There are literally dozens of options to ps and top to help you view process information exactly the way you want to. The pgrep command can further help find the process you want.

There are commands such as nice and renice for raising and lowering processor priority for a process. You can move processes to run in the background (bg command) or back to the foreground (fg command). On rare occasions, you can use the chrt command to run processes in realtime.

Sending signals to a process is a way of changing its behavior or killing it altogether. Using the kill and killall commands, you can send signals to processes by PID or name, respectively. You can also send other signals to processes to do such things as reread configuration files or continue with a stopped process.

To run commands at scheduled times or so they are not tied to your shell session, you can use the at and batch commands. To run commands repetitively at set times, there are the cron and anacron facilities. Or you can drop scripts (or symbolic links to scripts) into /etc/cron.hourly (or cron.daily, cron.weekly, or cron.monthly).

Listing Active Processes

To see which processes are currently running on a system, most people use the ps and top commands. The ps command gives you a snapshot (in a simple list) of processes running at the moment. The top command offers a screen-oriented, constantly updated listing of running commands, sorted as you choose (by CPU use, memory use, UID, and so on).

Viewing Active Processes with ps

Every Linux system (as well as every system derived from UNIX, such as BSD, Mac OS X, and others) includes the ps command. Over the years, however, many slightly different versions of ps have appeared, offering slightly different options. Because ps dates back to the first UNIX systems, it also supports nonstandard ways of entering some options (for example, allowing you to drop the dash before an option in some cases).

The different uses of ps shown in this chapter will work on Ubuntu and most other Linux systems. Here are some examples you can run to show processes running for the current user. (Table 9-1 contains column descriptions of ps output.)

$ ps List processes of current user at current shell

PID TTY TIME CMD

2552 pts/0 00:00:00 bash

3438 pts/0 00:00:00 ps

$ ps -u chris Show chris's running processes (simple output)

PID TTY TIME COMMAND

2678 tty1 0:00 startx

2689 tty1 0:00 xinit

2710 tty1 0:06 gnome-session

...

$ ps -u chris u Show all chris's running processes (with CPU/MEM)

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND

chris 2678 0.0 0.0 4328 852 tty1 S+ Aug14 0:00 /bin/sh startx

chris 2689 0.0 0.1 2408 488 tty1 S+ Aug14 0:00 xinit

chris 2710 0.0 1.1 22016 5496 tty1 S Aug14 0:06 gnome-session

...

$ ps -fu chris Show all chris's running processes (with PPID)

UID PID PPID C STIME TTY TIME CMD

chris 2678 2645 0 Aug14 tty1 00:00:00 /bin/sh /usr/X11R6/bin/startx

chris 2689 2678 0 Aug14 tty1 00:00:00 xinit /etc/X11/xinit/xinitrc

chris 2710 2689 0 Aug14 tty1 00:00:09 /usr/bin/gnome-session

...

$ ps -Fu chris Show chris's running processes (with SZ and PSR)

UID PID PPID C SZ RSS PSR STIME TTY TIME CMD

chris 2678 2645 0 1082 852 0 Aug14 tty1 00:00:00 /bin/sh startx

chris 2689 2678 0 602 488 0 Aug14 tty1 00:00:00 xinit

chris 2710 2689 0 5504 5440 0 Aug14 tty1 00:00:09 gnome-session

...

These examples illustrate some of the processes from a user running a GNOME desktop session. The first example in the preceding code shows ps alone being run from a Terminal window, so you see only the processes for the current shell running in that window. Other examples let you display different information for each process (see later examples for ways of producing custom output).

Here are ps examples showing output for every process currently running on the system:

$ ps -e Show every running process

PID TTY TIME CMD

1 ? 00:00:01 init

2 ? 00:00:00 migration/0

3 ? 00:00:00 ksoftirqd/0

...

$ ps -el Show every running process, long listing

F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD

4 S 0 1 0 0 75 0 - 534 - ? 00:00:01 init

1 S 0 2 1 0 -40 - - 0 - ? 00:00:00 migration/0

1 S 0 3 1 0 94 19 - 0 - ? 00:00:00 ksoftirqd/0

...

$ ps -ef Show every running process, full-format listing

UID PID PPID C STIME TTY TIME CMD

root 1 0 0 Aug05 ? 00:00:01 init [5]

root 2 1 0 Aug05 ? 00:00:00 [migration/0]

root 3 1 0 Aug05 ? 00:00:00 [ksoftirqd/0]

...

$ ps -eF Show every running process, extra full-format list

UID PID PPID C SZ RSS PSR STIME TTY TIME CMD

root 1 0 0 534 556 0 Aug05 ? 00:00:01 init [5]

root 2 1 0 0 0 0 Aug05 ? 00:00:00 [migration/0]

root 3 1 0 0 0 0 Aug05 ? 00:00:00 [ksoftirqd/0]

...

$ ps ax Show every running process, short BSD style

PID TTY STAT TIME COMMAND

1 ? Ss 0:01 init [5]

2 ? S 0:00 [migration/0]

3 ? SN 0:00 [ksoftirqd/0]

...

$ ps aux Show every running process, long BSD style

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND

root 1 0.0 0.0 2136 556 ? Ss Aug05 0:01 init [5]

root 2 0.0 0.0 0 0 ? S Aug05 0:00 [migration/0]

root 3 0.0 0.0 0 0 ? SN Aug05 0:00 [ksoftirqd/0]

...

$ ps auwx Show every running process, BSD style, wide format

$ ps auwwx Show every running process, BSD style, unlimited width

Some processes start up other processes. For example, a web server (httpd daemon) will spin off multiple httpd daemons to wait for requests to your web server. You can view the hierarchy of processes (in a tree view) using various options with ps:

$ ps -ejH Show process hierarchy with process/session IDs

PID PGID SID TTY TIME CMD

16267 16267 16267 ? 00:00:00 sshd

16462 16267 16267 ? 00:00:00 sshd

16463 16463 16463 pts/2 00:00:00 bash

16563 16563 16463 pts/2 00:00:00 firefox

16606 16606 16463 pts/2 00:00:00 sudo

16607 16606 16463 pts/2 00:00:00 su

16615 16615 16463 pts/2 00:00:00 bash

16673 16673 16463 pts/2 00:00:00 ps

$ ps axjf Show process hierarchy in BSD-style output

PPID PID PGID SID TTY TPGID STAT UID TIME COMMAND

1 957 957 957 ? -1 Ss 0 0:00 /usr/sbin/sshd -D

957 16267 16267 16267 ? -1 Ss 0 0:00 \_ sshd: chris [priv]

16267 16462 16267 16267 ? -1 S 1000 0:00 \_ sshd: chris@pts/

16462 16463 16463 16463 pts/2 16688 Ss 1000 0:00 \_ -bash

16463 16563 16563 16463 pts/2 16688 Sl 1000 0:02 \_ /usr/lib

16463 16606 16606 16463 pts/2 16688 S 0 0:00 \_ sudo su

$ ps -ef --forest Show process hierarchy in forest format

UID PID PPID C STIME TTY TIME CMD

root 957 1 0 Feb18 ? 00:00:00 /usr/sbin/sshd -D

root 16267 957 0 19:03 ? 00:00:00 \_ sshd: chris [priv]

chris 16462 16267 0 19:03 ? 00:00:00 \_ sshd: chris@pts/2

chris 16463 16462 0 19:03 pts/2 00:00:00 \_ -bash

chris 16563 16463 0 19:03 pts/2 00:00:02 \_ /usr/lib/firefox/

root 16606 16463 0 19:03 pts/2 00:00:00 \_ sudo su -

root 16607 16606 0 19:03 pts/2 00:00:00 \_ su -

$ pstree Show processes alphabetically in tree format

|−rsyslogd−−−3*[{rsyslogd}]

|−rtkit-daemon−−−2*[{rtkit-daemon}]

|−sound-juicer−−−3*[{sound-juicer}]

|−sshd−−−sshd−−−sshd−−−bash−┬−firefox−−−25*[{firefox}]

| └−sudo−−−su−−−bash−−−pstree

...

The “tree” examples just shown illustrate different ways of displaying the hierarchy of processes. The output was snipped to compare several of the same processes with different output. Note that the PPID (Parent Process ID) is the ID of the process that started each child process shown. The sshd processes show a running Secure Shell Daemon with a user logging in over the network, resulting in a bash shell starting. From that shell, the user starts a firefoxcommand in the background. Then the user opens a shell as super user (sudo su). The last example shows the pstree command, which is specifically used for displaying tree views of processes.

If you prefer personalized views of ps output, you can use the -o option to select exactly which columns of data to display with ps. You can then use the --sort option to sort the output by any of those data. Table 9-1 shows available column output and the options to add to -o to have each column print with ps.

Table 9-1: Selecting and Viewing ps Column Output

Option

Column Head

Description

%cpu

%CPU

CPU utilization of process’s lifetime in 00.0 format

%mem

%MEM

Percentage of system’s physical memory use (resident set size)

args

COMMAND

Command with all arguments

bsdstart

START

Start time of command started: “HH:MM” or “MonthDay” (for example, Jan 03)

bsdtime

TIME

Total (user and system) CPU time

comm

COMMAND

Command name only (no arguments shown)

cp

CP

CPU utilization in tenth-of-a-percentage

cputime

TIME

Total CPU time in [DD-]HH:MM:SS format

egid

EGID

Effective group ID of the process (as integer)

egroup

EGROUP

Effective group ID of the process (as name)

etime

ELAPSED

Time since process was started, in [[DD-]HH:]MM:SS format

euid

EUID

Effective user ID of the process (as integer)

euser

EUSER

Effective user ID of the process (as name)

fgid

FGID

Filesystem access group ID (as number)

fgroup

FGROUP

Filesystem access group ID (as name)

fname

COMMAND

First eight characters of command name

fuid

FUID

Filesystem access user ID (as number)

fuser

FUSER

Filesystem access user ID (as name)

lstart

STARTED

Date and time the command started

nice

NI

Nice value, from 19 (nicest) to -20 (CPU hog)

pgid

PGID

Process group ID of process

pid

PID

Process ID number of process

ppid

PPID

Parent process ID of process

psr

PSR

Processor process is assigned to (first CPU is 0)

rgid

RGID

Real group ID (as number)

rgroup

RGROUP

Real group (as name)

rss

RSS

Non-swapped physical memory (resident set size) in KB

rtprio

RTPRIO

Realtime priority

ruid

RUID

Real user ID (as number)

ruser

RUSER

Real user (as name)

s

S

One-character state display (D: sleep, no interrupt; R: running; S: sleep, can interrupt; T: stopped; W: paging; X: dead; Z: zombie)

sess

SESS

Session ID of session leader

sgi_p

P

Processor that process is currently running on

size

SZ

Rough amount of swap space needed if process were to swap out

start

STARTED

Time command started: HH:MM:SS or MonthDay

start_time

START

Time command started: HH:MM or MonthDay

stat

STAT

Multi-character state: One-character “s” state plus other state characters (<: High priority; N: Low priority; L: Has pages locked in memory; s: Is session leader; l: Multi-threaded; +: in foreground process group)

sz

SZ

Size of process’s core image (physical pages)

tname

TTY

Controlling tty (terminal)

user

USER

Effective user ID of process (as name)

vsize

VSZ

Process’s virtual memory (1024-byte units)

Note that some values that are meant to print usernames may still print numbers (UIDs) instead, if the name is too long to fit in the given space.

Using a comma-separated list of column options, you can produce your custom output. Here are some examples of custom views of running processes:

$ ps -eo ppid,user,%mem,size,vsize,comm --sort=-size Sort by mem

PPID USER %MEM SIZE VSZ COMMAND

1 root 0.0 1004292 1043060 console-kit-dae

6901 chris 2.3 713248 1125172 compiz

$ ps -eo ppid,user,bsdstart,bsdtime,%cpu,args --sort=-%cpu Sort by CPU

PPID USER START TIME %CPU COMMAND

6901 chris Feb 23 11:23 0.1 compiz

16463 chris 19:03 0:03 0.0 /usr/lib/firefox/firefox

1101 root Feb 18 14:31 0.0 /usr/bin/X :0 -auth ...

$ ps -eo ppid,user,nice,cputime,args --sort=-nice Sort by low priority

PPID USER NI TIME COMMAND

2 root 19 00:00:00 [khugepaged]

1 chris 10 00:00:31 /usr/bin/python /usr/bin/update-manager

2 root 5 00:00:00 [ksmd]

$ ps -eo ppid,user,stat,tname,sess,cputime,args --sort=user By user

PPID USER STAT TTY SESS TIME COMMAND

1 avahi S ? 851 00:00:09 avahi-daemon: running

1640 chris Ssl ? 6901 00:00:00 gnome-session --session=ubuntu

1 daemon Ss ? 1088 00:00:00 atd

846 lp S ? 846 00:00:00 /usr/lib/cups/notifier/dbus

0 root Ss ? 1 00:00:00 /sbin/init

Here are a few other examples of the ps command:

$ ps -C httpd Display running httpd processes

PID TTY TIME CMD

1493 ? 00:00:00 httpd

1495 ? 00:00:00 httpd

Note that you need to install an HTTP server, such as Apache, to run an httpd process.

$ ps -p 16563 -o pid,ppid,bsdtime,args Display info for PID 16565

PID PPID TIME COMMAND

16563 16463 0:04 /usr/lib/firefox/firefox

$ ps -U chris,avahi -o pid,ruser,tty,stat,args See info for 2 users

PID RUSER TT STAT COMMAND

852 avahi ? S avahi-daemon: running [ubuntutb.local]

853 avahi ? S avahi-daemon: chroot helper

6890 chris ? Sl /usr/bin/gnome-keyring-daemon

6901 chris ? Ssl gnome-session --session=ubuntu

Watching Active Processes with top

If you want to see the processes running on your system on an ongoing basis, you can use the top command. The top command runs a screen-oriented view of your running processes that is updated continuously. If you start the topcommand with no options, it displays your system’s uptime, tasks, CPU usage, and memory usage, followed by a list of your running processes, sorted by CPU usage. Here’s an example:

$ top

top - 2:37:18 up 2 days, 14:00, 3 users, load average: 0.00, 0.01, 0.05

Tasks: 178 total, 1 running, 177 sleeping, 0 stopped, 0 zombie

Cpu(s): 0.0%us, 0.2%sy, 0.0%ni, 99.7%id, 0.0%wa, 0.0%hi, 0.2%si, 0.0%st

Mem: 4014504k total, 2208972k used, 1805532k free, 161628k buffers

Swap: 4157436k total, 0k used, 4157436k free, 1388516k cached

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND

6967 chris 20 0 1213m 93m 29m S 0 2.4 11:24.95 compiz

16748 root 20 0 17340 1332 932 R 0 0.0 0:00.09 top

Here are examples of other options you can use to start top to continuously display running processes:

$ top -d 5 Change update delay to 5 seconds (from default 3)

$ top -u chris Only see processes of effective user name chris

$ top -p 190,2690 Only display processes 190 and 2690

$ top -n 10 Refresh the screen 10 times before quitting

$ top -b Run in batch mode

The last example (top -b) formats the output of top in a way that is suitable for output to a file, as opposed to redrawing the same screen for interactive viewing. This can be used to create a log of processes, for example when hunting down that runaway process that eats up all your resources in the middle of the night. Here’s how to run top and log the output 50 times:

$ top -b -n 50 > myprocesslog

When top is running, you can press keys to update and sort the process list in different ways:

· Press Space or Enter—Immediately updates the process list

· Press Shift+n—sorts by PID

· Press Shift+p—sorts by CPU usage

· Press Shift+m—sorts by memory usage

· Press Shift+t—sorts by CPU time consumed

· Press <—sorts the column to left characters

· Press >—sorts the column to right characters

· Press f plus the letter of the column—sorts by when the list of columns appears

There are several ways to change the behavior of top as it’s running:

· Press d and type a number—delays between refreshes in seconds represented by the number entered.

· Press u and a username—displays only processes for the selected user.

· Type n plus the number you want to see—displays only a select number of processes.

· Press =—returns to the original top display. You can do this at any point.

You can act on any of the running processes in different ways:

· Type k followed plus the PID—signals (kills) a running process.

· Type 9 (after the k)—ends the process.

· Type a different signal number (after k)—sends that signal to the process.

· Type n—gives a process higher or lower run priority. You type n and then add a negative number (to increase priority) or a positive number (to reduce priority).

If you want to find more information about how to use top, type ? during a top session. The man page also has a lot of information about how to use top:

$ man top View the top man page

When you are done using top, type q to exit.

Finding and Controlling Processes

Changing a running process first means finding the process you want to change, and then modifying the processing priority or sending the process a signal to change its behavior. If you are looking for a particular process, you might find it tough to locate it in a large list of processes output by ps or top.

The pgrep command offers ways of searching through your active processes for the ones you are looking for. The renice command lets you change the processing priority of running processes. The kill, pkill, and killallcommands let you send signals to running processes (including signals to end those processes).

Using pgrep to Find Processes

In its most basic form, you can use pgrep to search for a command name (or part of one) and produce the process ID of any process that includes that name. For example:

$ pgrep init Show PID for any process including 'init' string

1

2689

Because you know there is only one init command running, you next use the -l option to see each process’s command name (to learn why two processes showed up):

$ pgrep -l init Show PID and name for processes including init

1 init

2689 xinit

You can also search for processes that are associated with a particular user:

$ pgrep -lu chris List all processes owned by user chris

16462 sshd

16463 bash

16563 firefox

Probably the most useful way to use pgrep is to have it find the process IDs of the running processes and pipe those PIDs to another command to produce the output. Here are some examples (look for other commands if sshd or firefox aren’t running):

$ ps -p `pgrep sshd` Search for sshd and run ps (short)

PID TTY STAT TIME COMMAND

957 ? Ss 0:00 /usr/sbin/sshd -D

16267 ? Ss 0:00 sshd: chris [priv]

16462 ? R 0:00 sshd: chris@pts/2

$ ps -fp $(pgrep firefox) Search for firefox and run ps (full)

UID PID PPID C STIME TTY TIME CMD

chris 16563 16463 0 19:03 pts/2 00:00:05 /usr/lib/firefox/firefox

$ sudo renice -5 $(pgrep firefox) Search for firefox, improve priority

16563 (process ID) old priority 0, new priority -5

Any command that can take a process ID as input can be combined with pgrep in these ways. As the previous example of pgrep illustrates, you can use commands such as renice to change how a process behaves while it is running.

Using fuser to Find Processes

Another way to locate a particular process is by what the process is accessing. The fuser command can be used to find which processes have a file or a socket open at the moment. After the processes are found, fuser can be used to send signals to those processes.

The fuser command is most useful for finding out if files are being held open by processes on mounted filesystems (such as local hard disks or Samba shares). Finding those processes allows you to close them properly (or just kill them if you must) so the filesystem can be unmounted cleanly. (If the fuser command is not found, install the psmisc package.)

Here are some examples of the fuser command for listing processes that have files open on a selected filesystem:

$ sudo fuser -mauv /boot Verbose output of processes with /boot open

USER PID ACCESS COMMAND

/boot: root kernel mount (root)/boot

root 16615 ..c.. (root)bash

root 17289 ..c.. (root)vi

The example just shown displays the process ID for running processes associated with /boot. They may have a file open, a shell open, or be a child process of a shell with the current directory in /boot. Specifically in this example, there is a bash shell open in the /boot filesystem and one vi command with files open in /boot. The -a shows all processes, -u indicates which user owns each process, and -v produces verbose output.

Here are other examples using fuser to show processes with files open:

$ fuser -m /boot Show all PIDs for processes opening /boot

/boot: 16615c 17289c 17312c

$ sudo fuser -um /boot Show PIDs/user for this shell open in /boot

/boot: 16615c(root) 17289c(root) 17312c(root)

After you know which processes have files open, you can close those processes manually or kill them. Close processes manually if at all possible because simply killing processes can leave files in an unclean state! Here are examples of using fuser to kill or send other signals to all processes with files open to a filesystem:

$ sudo fuser -k /boot Kill processes with /boot files open

$ fuser -l List supported signals

HUP INT QUIT ILL TRAP ABRT IOT BUS FPE KILL USR1 SEGV USR2 PIPE ALRM

TERM

STKFLT CHLD CONT STOP TSTP TTIN TTOU URG XCPU XFSZ VTALRM PROF

WINCH IO

PWR SYS UNUSED

$ sudo fuser -k -HUP /boot Send HUP signal to processes with /boot open

Changing Running Processes

Even after a process is running, you can change its behavior in different ways. With the renice command, shown earlier, you can adjust a running process’s priority in your system’s scheduler. With the nice command, you can determine the default priority and also set a higher or lower priority at the time you launch a process.

Another way you can change how a running process behaves is to send a signal to that process. The kill and killall commands can be used to send signals to running processes. Likewise, the pkill command can send a signal to a process.

Adjusting Processor Priority with nice

Every running process has a nice value that can be used to tell the Linux process scheduler what priority should be given to that process. Positive values of niceness actually give your process a lower priority. The concept came about during the days of large, multi-user UNIX systems where you could be “nice” by running a non-urgent process at a lower priority so other users had a shot at the CPU.

Niceness doesn’t enforce scheduling priority, but is merely a suggestion to the scheduler. To see your current default nice value, you can type the nice command with no options:

$ nice Run nice to determine current niceness

0

The default nice value is 0. You can use the nice command to run a process at a higher or lower priority than the default. The priority number can range from -20 (most favorable scheduling priority) to 19 (least favorable scheduling priority). Although the root user can raise or lower any user’s nice value, a regular user can only lower the priorities of a process (setting a higher nice value).

Here are a few examples of starting a command with nice to change a command’s nice value:

$ nice -n 12 nroff -man a.roff | less Format man pages at low priority

$ sudo nice -n -10 gimp Launch gimp at higher priority

When a process is already running, you can change the process’s nice value using the renice command. Here are some examples of the renice command:

$ renice +2 -u chris Renice chris's processes +2

$ renice +5 4737 Renice PID 4737 by +5

$ sudo renice -3 `pgrep -u chris spamd` Renice chris's spamd processes

9688: old priority -1, new priority -3

20279: old priority -1, new priority -3

2: old priority -1, new priority -3

The backticks are used in the previous command line to indicate that the output of the pgrep command (presumably PIDs of spamd daemons run by chris) is fed to the renice command.

The niceness settings for your processes are displayed by default when you run top. You can also see niceness settings using -o nice when you produce custom output from the ps command.

Running Processes in the Background and Foreground

When you run a process from a shell, it is run in the foreground by default. That means that you can’t type another command until the first one is done. By adding an ampersand (&) to the end of a command line, you can run that command line in the background. Using the fg, bg, and jobs commands, along with various control codes, you can move commands between background and foreground.

In the following sequence of commands, you can start the GIMP image program from a Terminal window. After that is a series of control keys and commands to stop and start the process and move it between foreground and background:

$ gimp Run gimp in the foreground

<Ctrl+z> Stop process and place in background

[1]+ Stopped gimp

$ bg 1 Start process running again in background

$ fg 1 Continue running process in foreground

gimp

<Ctrl+c> Kill process

Note that processes placed in the background are given a job ID number (in this case, 1). By placing a percentage sign in front of the number (for example, %1) you can identify a particular background process to the bg and fgcommands, or you can simply type the number with the command (as in fg 1). With one or more background jobs running at the current shell, you can use the jobs command to manage your background jobs:

$ jobs Display background jobs for current shell

[1] Running gimp &

[2] Running xmms &

[3]- Running gedit &

[4]+ Stopped gtali

$ jobs -l Display PID with each job's information

[1] 31676 Running gimp &

[2] 31677 Running xmms &

[3]- 31683 Running gedit &

[4]+ 31688 Stopped gtali

$ jobs -l %2 Display information only for job %2

[2] 31677 Running xmms &

The processes running in the jobs examples might have been started while you were logged in (using ssh) to a remote system. Some of those processes you might want to run as remote GUI applications on your local desktop. By running those processes in the background, you can have multiple applications running at once while still having those applications associated with your current shell. Once a process is running, you can disconnect the process from the current shell using the disown command:

$ disown %3 Disconnect job %3 from current shell

$ disown -a Disconnect all jobs from current shell

$ disown -h Protect all jobs from HUP sent to current shell

After you have disowned a process, you can close the shell without also killing the process.

The fg and bg commands manipulate running processes by moving those processes to the foreground or background. Another way to manipulate running commands is to send signals directly to those processes. A common way to send signals to running processes is with the kill and killall commands.

Killing and Signaling Processes

You can stop or change running processes by sending signals to those processes. Commands such as kill and killall can send signals you select to running processes, which as their names imply, is often a signal to kill the process.

Signals are represented by numbers (9, 15, and so on) and strings (SIGKILL, SIGTERM, and so on). Table 9-2 shows standard signals you can send to processes in Linux.

Table 9-2: Standard Signals to Send to Processes

Signal Number

Signal Name

Description

1

SIGHUP

Hang up from terminal or controlling process died

2

SIGINT

Keyboard interrupt

3

SIGQUIT

Keyboard quit

4

SIGILL

Illegal instruction

6

SIGABRT

Abort sent from abort function

8

SIGFPE

Floating point exception

9

SIGKILL

Kill signal

11

SIGSEGV

Invalid memory reference

13

SIGPIPE

Pipe broken (no process reading from pipe)

14

SIGALRM

Timer signal from alarm system call

15

SIGTERM

Termination signal

30, 10, 16

SIGUSR1

User-defined signal 1

31, 12, 17

SIGUSR2

User-defined signal 2

20, 17, 18

SIGCHLD

Child terminated or stopped

19, 18, 25

SIGCONT

Continue if process is stopped

17, 19, 23

SIGSTOP

Stop the process

18, 20, 24

SIGTSTP

Stop typed at terminal

21, 21, 26

SIGTTIN

Terminal input for background process

22, 22, 27

SIGTTOU

Terminal output for background process

The kill command can send signals to processes by process ID or job number while the killall command can signal processes by command name. Here are some examples:

$ kill 28665 Send SIGTERM to process with PID 28665

$ kill -9 4895 Send SIGKILL to process with PID 4895

$ kill -SIGCONT 5254 Continue a stopped process (pid 5254)

$ kill %3 Kill the process represented by job %3

$ killall spamd Kill all spamd daemons currently running

$ killall -SIGHUP sendmail Have sendmail processes reread config files

The SIGKILL (-9) signal, used generously by trigger-happy novice administrators, should be reserved as a last resort. It does not allow the targeted process to exit cleanly but forces it to end abruptly. This can potentially result in loss or corruption of data handled by that process. The SIGHUP signal was originally used on UNIX systems to indicate that a terminal was being disconnected from a mainframe (such as from a hang-up of a dial-in modem). However, daemon processes, such as sendmail and httpd, were implemented to catch SIGHUP signals as an indication that those processes should reread configuration files.

Running Processes Away from the Current Shell

If you want a process to continue to run, even if you disconnect from the current shell session, there are several ways to go about doing that. You can use the nohup command to run a process in a way that it is impervious to a hang-up signal:

$ nohup updatedb & Run updatedb with no ability to interrupt

# nohup nice -9 gcc hello.c & Run gcc uninterrupted and higher priority

Using nohup is different than running the command with an ampersand alone because with nohup the command will keep running, even if you exit the shell that launched the command.

The nohup command was commonly used in the days of slow processors and dial-up connections (so you didn’t have to stay logged in to an expensive connection while a long compile completed). Also, today using tools such as screen (described in Chapter 13) you can keep a shell session active, even after you disconnect your network connection to that shell. So nohup isn’t used as often as it once was.

Scheduling Processes to Run

Commands associated with the cron facility can be used to set a command to run at a specific time (including now) so that it is not connected to the current shell. The at command runs a command at the time you set:

$ at now +1 min Start command running in one minute

at> updatedb

at> <Ctrl+d> <EOT>

job 5 at Sat Mar 2 20:37:00 2013

$ at teatime Start command at 4pm today

$ at now +5 days Start a command in five days

$ at 06/25/13 Start a command at current time on June 25, 2013

Another way to run a command that’s not connected with the current shell is with the batch command. With batch, you can set a command to start as soon as the processor is ready (load average below .8):

$ batch Start command running immediately

at> find /mnt/isos | grep jpg$ > /tmp/mypics

at> <Ctrl+d> <EOT>

Note that after the at or batch commands you see a secondary at> prompt. Type the command you want to run at that prompt and press Enter. After that, you can continue to enter commands. When you are done, press Ctrl+d on a line by itself to queue the commands you entered to run.

After the commands are entered, you can check the queue of at jobs that are set to run by typing the atq command:

$ atq

11 Thu Sep 5 21:10:00 2013 a chris

10 Sat Aug 24 21:10:00 2013 a chris

8 Fri Aug 23 20:53:00 2013 a chris

Regular users can only see their own at jobs that are queued. The root user can see everyone’s queued at jobs. If you want to delete an at job from the queue, use the atrm command:

$ atrm 11 Delete at job number 11

The at and batch commands are for queuing up a command to run as a one-shot deal. You can use the cron facility to set up commands to run repeatedly. These commands are scripted into cron jobs, which are scheduled in crontab files. There is one system crontab file (/etc/crontab). Also, each user can create a personal crontab file that can launch commands at times that the user chooses. To create a personal crontab file, type the following:

$ crontab -e Create a personal crontab file

The crontab -e command opens your crontab file (or creates a new one) using the vi text editor. Here are examples of several entries you could add to a crontab file:

15 8 * * Mon,Tue,Wed,Thu,Fri mail chris < /var/project/stats.txt

* * 1 1,4,7,10 * find / | grep .doc$ > /var/sales/documents.txt

The first crontab example shown sends a mail message to the user named chris by directing the contents of /var/project/stats.txt into that message. That mail command is run Monday through Friday at 8:15 a.m. In the second example, on the first day of January, April, July, and October, the find command runs to look for every .doc file on the system and sends the resulting list of files to /var/sales/documents.txt.

The last part of each crontab entry is the command that is run. The first five fields represent the time and date the command is run. The fields from left to right are: minute (0 to 59), hour (0 to 23), day of the month (0 to 31), month (0 to 12 or Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, or Dec), and day of the week (0 to 7 or Sun, Mon, Tue, Wed, Thu, Fri, or Sat). An asterisk (*) in a field means to match any value for that field.

If there is output from the command that is run, and you don’t direct that output to a file or another command, by default the output is sent to the user running the cron command. To set a specific e-mail address to receive the output, you can add a MAILTO line to the crontab file. For example:

MAILTO=chris@example.com

Here are some other options with the crontab command:

# crontab -eu chris Edit another user's crontab (root only)

$ crontab -l List contents of your crontab file

15 8 * * Mon,Tue,Wed,Thu,Fri mail chris < /var/project/stats.txt

* * 1 1,4,7,10 * find / | grep .doc$ > /var/sales/documents.txt

$ crontab -r Delete your crontab file

The traditional way to configure system cron jobs was to add them to the system crontab. Although this is still an option, Ubuntu provides an easier way to create hourly, daily, weekly, and monthly cron jobs, by associating the command you want to run with a cron directory. Simply create a script that you want to run. Then copy the script to the /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly, or /etc/cron.monthly directory. The command will then run in the time frame indicated by the directory (hourly, daily, weekly, or monthly).

An alternative to the cron facility is the anacron facility. With anacron, as with cron, you can configure commands to run periodically. However, anacron is most appropriate for machines that are not on all the time. If a command is not run because the computer was off during the scheduled time, the next time the computer is on, the anacron facility makes sure that the commands that were missed during the downtime are run after the system resumes.

Scheduling Realtime Processes

The order processes are run, and the amount of attention they get from the CPUs is determined by the process scheduler. In most cases, adjusting the nice value on regular processes (those running under the standard SCHED_OTHERpolicy) is the only change you need to give a process higher or lower priority to the processor. (See the section “Adjusting Processor Priority with nice” earlier in this chapter.)

In some rare cases, however, you might want to assign a special policy to a process. While some of those policies reduce the amount of attention processes get from the CPUs (for example, some long-running batch jobs that are not time critical), other policies are what is referred to as realtime policies, which get a process ahead of any SCHED_OTHER processes running on the system.

Note Setting realtime priority to a process should not be done on production systems unless you are sure of what you are doing. These processes will preempt system processes and can make your system unstable or even unusable if done incorrectly.

Processor policies in Linux include the following:

· SCHED_OTHER—All processes receive this scheduling on basic Linux time-sharing systems unless another scheduling type is assigned. Order of processing is based on nice value.

· SCHED_BATCH—Processes set to this priority get less favor in scheduling, assuming the processes demand a lot of CPU but can wait for attention. Processes within this policy are scheduled based on nice value (although they would get less attention than processes of the SCHED_OTHER policy).

· SCHED_IDLE—Processes in this policy get very low priority (after even SCHED_OTHER and SCHED_BATCH processes set to 19 nice value).

· SCHED_FIFO—Any processes set to this realtime processor policy will preempt any running SCHED_OTHER, SCHED_BATCH, and SCHED_IDLE process. Within the SCHED_FIFO policy, processes are scheduled first in, first out.

· SCHED_RR—This realtime process is like SCHED_FIFO, except that processes in this policy share the CPU with each other. In other words, one SCHED_RR process need not complete before another SCHED_RR process can run.

Using the chrt command, you can see which of the five Linux scheduling policies is assigned to a command. You can also use chrt to change the scheduling policy on a running process or start a process with a particular scheduling policy.

To read more about process scheduling, see the chrt and sched_setschedule man pages.

Change a Process to a Realtime Process

The following commands find the process ID of a regular process you want to make into a realtime process, list its scheduling policy, and change its policy:

$ pidof firefox Find process ID of the firefox process

16563

$ chrt -p 16563 List scheduling policy of process

pid 16563's current scheduling policy: SCHED_OTHER

pid 16563's current scheduling priority: 0

$ chrt -m List scheduling policies and ranges

SCHED_OTHER min/max priority : 0/0

SCHED_FIFO min/max priority : 1/99

SCHED_RR min/max priority : 1/99

SCHED_BATCH min/max priority : 0/0

SCHED_IDLE min/max priority : 0/0

$ sudo chrt -r -p 20 16563 Change round robin realtime process

$ chrt -p 16563 View new round robin realtime process

pid 16563's current scheduling policy: SCHED_RR

pid 16563's current scheduling priority: 20

$ sudo chrt -f -p 10 16563 Change to fifo realtime process

Start a Process as a Realtime Process

To start a process at a particular priority, you can use chrt when you first start the process.

$ sudo chrt -r 50 firefox Start at round-robin priority 50

$ sudo chrt -f 99 gcc hello.c Start at fifo priority 99

Summary

Watching and working with the processes that run on your Linux system are important activities to make sure that your system is operating efficiently. Using commands such as ps and top, you can view the processes running on your system. You can also use pgrep to search for and list particular processes.

With commands such as nice and renice, you can adjust the recommended priorities at which selected processes run. When a process is running, you can change how it is running or kill the process by sending it a signal from the kill or killall command.

After launching a command from the current shell, you can set that command’s process to run in the background (bg) or foreground (fg). You can also stop and restart the process using different control codes.

To schedule a command to run at a later time, you can use the at or batch command. To set up a command to run repeatedly at set intervals, you can use the cron or anacron facilities. To run commands at different scheduling priorities, use the chrt command.