Process Management - CompTIA Linux+ / LPIC-1 Cert Guide (Exams LX0-103 & LX0-104/101-400 & 102-400) (2016)

CompTIA Linux+ / LPIC-1 Cert Guide (Exams LX0-103 & LX0-104/101-400 & 102-400) (2016)

Chapter 7. Process Management

This chapter covers the following topics:

Image Managing Processes

Image Sending Signals to Processes

Image Job Control

Image Managing Process Priorities

Image Leaving Programs Running after Logout

This chapter covers the following objectives:

Image Create, monitor, and kill processes: 103.5

Image Modify process execution priorities: 103.6

Processes and process management are key to a sysadmin’s daily work, in that almost everything that runs on your system can be viewed as a process, a hierarchy of related processes, or interrelated processes that depend on each other to be present, working, and responsive.

“Do I Know This Already?” Quiz

The “Do I Know This Already?” quiz enables you to assess whether you should read this entire chapter or simply jump to the “Exam Preparation Tasks” section for review. If you are in doubt, read the entire chapter. Table 7-1 outlines the major headings in this chapter and the corresponding “Do I Know This Already?” quiz questions. You can find the answers in Appendix A, “Answers to the ‘Do I Know This Already?’ Quizzes.”

Image

Table 7-1 “Do I Know This Already?” Foundation Topics Section-to-Question Mapping

1. Which of the following commands can show you a treelike hierarchy of processes and information about them? (Choose all that apply.)

a. procheir

b. lsproc

c. ps

d. pstree

e. gvfs-tree

2. Which of the following sets of keystrokes pause or stop a program’s execution and allow you to run job control on it?

a. Ctrl-c

b. Ctrl-z

c. Ctrl-p

d. Ctrl-q

e. Ctrl-f

3. When you run the jobs command, you see the following output:

linux-8z04:~ # jobs
[1]- Stopped top
[2]+ Stopped vim
[3] Running strace top &

If you were to run the fg command at this time, what would happen?

a. The top command would be brought to the foreground.

b. The strace command would be brought to the foreground.

c. Nothing.

d. The vim command would be brought to the foreground.

4. As the sysadmin of a system, you notice in the top command output that a particular command is using an inordinate amount of system resources. Which of the following keystrokes or commands would alter the process priority for the unruly command? (Choose two.)

a. nice

b. renice

c. ps -nice

d. r

e. kill -nice

5. You are tasked with running a large set of automated reports that have been scripted to be run as the root user. From experience, you know that these reports often take longer than the 8-hour workday, and you’re on salary now so you’re uninterested in pulling an all-nighter.

Which of the following commands would let you run your script unattended, even after you log out for the evening? (Choose all that apply.)

a. nohup

b. exec

c. screen

d. unattend

e. control

Foundation Topics

Managing Processes

Managing programs and processes is essential to running a Linux machine. Various utilities can help you manage those processes. Let’s begin with viewing processes and then move on to removing processes. Finally, we affect process priorities.

Image

Viewing Processes

When you need to see what’s running on your machine, regardless of any GUI tools or programs, you can use the ps command. The ps command is used to display process information and has switches to format the output.

For example, to show the processes started by this user and the user’s shell, just type the ps command, like so:

ps
PID TTY TIME CMD
19856 pts/0 00:00:00 bash
20057 pts/0 00:00:00 ps

This is the simplest view of your system’s processes, but it leaves out a lot of backgrounded or nonterminal-associated processes. The -a option shows essentially any process that the current user has started besides the actual bash shell. Use the following to show progressively more information:

ps –a
PID TTY TIME CMD
1497 tty1 00:00:00 startx
1510 tty1 00:00:00 xinit
1523 tty1 00:00:00 gnome-session
1528 tty1 00:00:00 xinitrc <defunct>
15075 pts/1 00:00:00 ps
... output truncated for readability.

Obviously, you got more information because a switch is used for showing all processes that are terminal-bound. That means if another user is on the system, you can see her processes listed too.

Now type the following:

ps –a | wc –l
66

The important number is the one reported by the wc command: It’s the number of lines in the output. Each one represents a running process. This machine has 66 processes found by the ps command.

Image

More ps command switches to know are as follows:

Image a—Shows all processes for all users

Image u—Shows user information for processes

Image x—Shows processes without a controlling tty

What’s the Diff?

There’s a lot of confusion among junior sysadmins about why you use ps aux sometimes and ps -aux at other times.

The man page isn’t very helpful either, but it does tell you why the dash is used and why it’s not. Linux’s version of the ps command is a latecomer. There are two main parents to this version: BSD and POSIX, offering differing but similar ways of doing commands and options.

The BSD style of using options with the ps command is that you can group them, aka “aux,” but they must not use a preceding dash. The POSIX or UNIX method is that you can group them, again “aux,” but they must be preceded with a dash, as in ps -aux.

In short, the two methods are similar, and Linux’s version of ps allows for either method.

Use the pstree command to show the hierarchical nature of the processes on the system, such as the following example:

init-+-apmd
|-atd
|-bdflush
|-bonobo-activati
|-crond
|-cupsd
|-dhcpcd
|-evolution-alarm
|-gconfd-2
|-gnome-cups-mana
|-gnome-name-serv
|-gnome-panel
|-gnome-settings-
|-gnome-smproxy
|-gnome-terminal-+-bash
| `-mgt-pty-helper


Note

The ps and pstree commands have many options. It’s good to be aware of as many as possible, especially for when you take the exam. Both commands have the capability of showing the system’s running processes in a treelike or hierarchical fashion.


Image

Attention, older or seasoned Unix users: There will likely be questions that test how well you know the ps command, including what Linux uses as the equivalent of the command:

ps –ef

Verify how similar ps –ef is to ps aux with the following:

ps –ef > psef
ps –aux > psaux
vimdiff psef psaux

You find a number of similarities between the two output streams. The ps aux command is from Linux, whereas ps –ef originates from Unix.

Image

The free Command

The free command is used to determine the amount of free memory on the system, not just by displaying the amount of unused system RAM, but also by giving you more detailed information about how much free and in-use physical memory you have, how much swap space or disk-based fake memory is in use, and finally how much of the used system RAM is being taken up by buffers and caches.

There is a moment in every class we teach where the student/attendee looks at the output of the free command and gets a quizzical look on her face, because she can’t reconcile the actual amount of RAM in use on the system with the current load. We always take the time to explain that system RAM on a lightly utilized system is like a bus that is only half full of passengers. Everyone has room in the seat next to them for magazines, snacks, and drinks and ample room to stretch out a bit.

We then make the correlation between the passenger and a running process, and the room the passenger has allocated to her is similar to the working set (everything needed to run) for a process. The key here is that when lightly loaded, the system can allocate otherwise unused system RAM to handy and useful items such as cache and buffers, and the processes can stretch out a bit and have fully loaded working sets for efficient running of that process.

Blocks and Buffers

Key to the running of processes and the speed of processing on the system are blocks and buffers. Block devices such as disks have an addressable unit called a block. This is typically (not always, but often) 512 bytes in size. System software also uses a construct called a block, but it’s typically much larger than the physical size of a block on a hard disk or other block device.

When a disk block is read into system memory, it’s stored in what is called a “buffer.” Buffers are associated with one and only one block, and that buffer is how the data contained in that block is addressed while in memory.

Pages, Slabs, and Caches

Pages are how the kernel manages memory on your system. The processor can address very small units of memory, aka a “word” or “byte,” but the memory management unit uses pages and only addresses memory in page-sized chunks. The kernel addresses every single page of the memory in the struct_page table and includes information critical to managing that page in each page’s entry there.

Pages are frequently populated with the same data, read from buffers and written back to caches for later reading. The system manages its own structure and marks pages as being used, free, or a number of other flags or parameters entirely secondary to our purpose here.

Caches are made up of slabs, which are one or more contiguous pages, although most of the time a slab is only one page. To illustrate the relationship between a cache and a slab, we can say the cache is a city, the slab is a neighborhood, and the page is a block in that neighborhood.

To sum this all up, blocks are a data location on disk, buffers are what blocks are read into when a file or set of files is requested from disk, and then when those buffers are read into a page in memory, that page is a part of a slab or set of slabs that make up a cache.

To continue the bus and passenger analogy, remember that a lightly loaded system shows a large utilization of RAM but also a correspondingly hefty use of cache and buffers, while a heavily loaded system, one with many processes running, shows a lot of RAM in use but relatively low cache and buffers. Effectively, as you load up the system with more processes, all the passengers/processes have to tighten up their working sets, put their magazines, snacks, extra luggage, and drinks in the overhead rack or under the seat and be respectful of their fellow passengers/processes.

Interpreting Displayed Information from free

Image

free has a number of options, but before showing you execution examples, it’s important to discuss and define the columns of output you see.

total Total installed memory (MemTotal and SwapTotal in /proc/
meminfo)
used memory (calculated as total - free)
free Unused memory (MemFree and SwapFree in /proc/meminfo)
shared Memory used (mostly) by tmpfs (Shmem in /proc/
meminfo, available on kernels 2.6.32, displayed as zero if not
available)
buffers Memory used by kernel buffers (Buffers in /proc/
meminfo)
cached Memory used by the page cache (Cached in /proc/
meminfo)

These definitions are from the free man page, and as you look at the following, remember that all this information is available in raw formats in the /proc/meminfo directory in the various files mentioned. All the free command does is read that data and display it in a more organized and configurable manner for your viewing pleasure.


Note

The free command is like a number of other system utilities. It allows you to display its counts or data in a couple of modes, the first being “here’s a huge number in bytes, good luck converting that to something mere humans can understand.” Or you can just use the -h option; it converts the numeric values into bytes, kilobytes, megabytes, gigabytes, and even terabytes, as shown in Figure 7-1. You may see this referenced on an exam item, so pay close attention to the examples.


Image

Figure 7-1 Running the free command with the -h option

Look at the total column in Figure 7-1. That’s the total RAM on the virtual machine we are running the free command on. The next two columns, used and free, tell you exactly how much RAM is being used and what remains not in use.

The buffers and cached columns are the amount of RAM currently being used to store the cache and buffers, and these will likely change over time and with differing amounts of loads. If you want to see some of these items change, in particular the cached column, execute the find / -iname “.txt” command to find every text file on your system you have access to, and you’ll see the cached column expand as it predictively loads a lot of files that the system now assumes you might read or use another utility upon.

Then run the free command again to see the changes made to the numbers, particularly the cached column, as many files were found and predictively cached in case you might need to read them, and that read would be from memory, not from disk.

Image

Additionally, you can use the --lohi long option to get a more detailed summary of the information. It’s helpful to also include the -h option to get the summary information in kb/mb/gb etc (see Figure 7-2).

Image

Figure 7-2 Running the free command with the --lohi option

System Uptime

The obvious usage for the uptime command is to determine how long the system has been “up” or running since reboot.

What’s not obvious but is handy information is the number of users currently on the system and the average number of jobs in the run queue for the processor(s) over the last 1/5/15 minutes.

Image

The jobs in the run queue information can be helpful in determining why a system might be slow, or seem sluggish. Too many jobs in the queue means that either the system is heavily overloaded or undergoing a lot of wait time for data to be read from disk, rather than from caches in memory, as per the previous section.

A possible fix for this is to start monitoring the number of processes and how much swap space is being used. A higher number of processes and an active amount of swap in use, not allocated but actually in use, indicates the system is overloaded.

A lightly loaded system returns uptime output similar to the following:

14:22pm up 3 days 3:34, 3 users, load average: 0.00, 0.02, 0.05


Note

I know some sysadmins who have a cron job that runs top and uptime once every 30 minutes, and sends the output to them as an email, just so they can periodically see what is happening without constantly monitoring the system. This is a quick and easy way to get important information.


Sending Signals to Processes

Traditionally, when learning about signals and processes, you’re introduced to a list of signals, with the explanations to the right of the signal, and then taught about the kill and killall commands. If you’re lucky and your teacher likes to use pgrep or pkill, you learn a bit about those as well.

Table 7-2 shows the commonly used signal names, their numeric equivalents, and what the signal does to a process.

Image

Image

Table 7-2 List of Common Linux Signals

The most common way to send a signal to a given process is by pressing the Ctrl-C keys while the command or script is processing and not interrupting the process unnecessarily. If you wait a reasonable amount of time and nothing happens, or the process seems locked up, by all means interrupt the process; just be aware you might lose a small bit of data or suffer other unintended consequences.


Note

Obviously, if you are running a data-generating command, interruption might be of consequence, but merely interrupting a long file search or output command is relatively risk free.


Another common method of sending a signal to a running process is to use the Ctrl-z keystrokes to send the process a SIGTSTP or 20 signal, effectively pausing the process, which will most often then be backgrounded by the bg command, as in job control. This is covered in the “Job Control” section later in the chapter.

Killing Processes by PID

The normal method for stopping a process is to use either the kill or killall utility to send a polite kill to it. When you encounter a process that can’t be removed from memory, because it’s not receiving signals or perhaps due to sheer orneriness, you need to kill the process and remove it from memory.

Remember, the kill and killall commands simply send a signal to the process—they don’t actually remove the processes themselves.

Image

The default kill signal is number 15, and the signal name is SIGTERM. This politely requests the process to end, allowing it to clean up its memory. If you type the kill command and the process ID (PID) of a program, the 15 or SIGTERM signal is sent to that program.

The SIGHUP, HUP, or 1 signal is a special case. It’s what we could call a bounce signal, where the process isn’t just killed but instead is signaled to end and then restart itself. The most frequently used reason for doing this is to have a process such as a server daemon stop, reread its configuration files, and then start back up. You can specify this signal by either -1 or -hup.

kill -1 PID or kill –HUP PID(bounces or restarts processes)


Note

Many a server admin has had to “bounce” a service on a server, either to reread a configuration file or to get the service working again after it mysteriously stopped working. Exam-takers will likely see this; it’s a commonly missed section of this topic.


Image

The SIGKILL or 9 signal is the ultimate kill signal. Even if a process is a zombie (can’t be killed by any other means), a kill -9 PID command usually kills the process and removes it from memory. The process being SIGKILLed has no opportunity to save data or do anything else.

kill -9 PID or kill –KILL PID (puts a bullet in the process,
no saves)

Killing Processes by Other Criteria

Sometimes you can’t kill a process by the PID—either it’s unavailable or you can’t find it in the process table using the ps command and so on. Other times, there may be so many similarly named processes that you don’t want to take the considerable time it would entail to kill them all by PID, or you don’t really care which process it is; you want to clean house of that particular sort of named or similar process and reexecute the command.

Image

The most common way to kill multiple similarly named processes is the killall command. I used to joke that the command was created by an insanely frustrated Netscape Communicator user who had programming skills, so he could clear off all the “netscape” processes on his machine and restart the browser, but this might not be completely true. (Although, from my experience, it should be.) You might experience this problem with Google’s Chrome browser, so if you prefer, use Chrome in your killall commands.

Using killall is simple. You can run ps aux and find out the name(s) of the processes you want to kill and then use the killall command followed by the name, such as:

killall processname

On a more elegant or complex level, you can use the pkill or process kill command, which isn’t just limited to the use of the process’s command name but can find and send signals to processes based on numerous criteria, including

Image Process name

Image Process ID

Image Username

Image Process or session ID

Image Terminal

Image

Usage of pkill is not that complex, but if you use multiple criteria, such as username and controlling terminal, all the criteria must match, or the signal won’t be sent. The pkill command has a companion app, pgrep, which is most often used to test out your desired pkill command before figuratively pulling the trigger on it.

Image

Another great and useful feature of pgrep is that you can use it to find processes and then feed them to another command, such as renice. As an example, to find all running Chrome browser processes and change the priority level on them, you could use the following command:

renice +5 'pgrep chrome'

This finds all the “chrome” named processes in the process table and executes the renice +5 command on them, effectively dropping their priority from the default.

When using pkill, you typically use the same command and options used with pgrep, only pkill goes ahead and executes the signal pass on the process, instead of sending the output to stdout or the console, like pgrep usually does.


Note

A quick warning about using killall or pkill as the root user: If you do run the command as root, it kills all the processes on the system that match the criteria, regardless of the owner, which may not be what you wanted. It also introduces you to all your users, as they call to ask what happened on the server. The safest way to run these commands are as a normal user or very carefully as the root user.


Job Control

Job control was invented when users had access to only a single terminal and getting more work done usually required another terminal. Job control allows the user to run multiple commands in a background mode while working in the foreground application.

When using the shell, a program can be run, suspended, and then put into the background, or the command can be invoked and put into the background in one step.

Image


Note

When you are putting commands into the background, you use the & character at the end of the command line, separated by a space, such as command1 -option &. This will background the command at execution time.


The following steps show how to use job control:

1. Start a task such as an editor.

2. Suspend the program by pressing Ctrl+Z.

3. Execute the jobs command to see the status:

jobs
[1]+ Stopped vim

4. Send job # 1 to the background by typing bg and pressing Enter:

bg
[1]+ vim &

5. Now start another program such as top in the background with the following:

top &

6. Run the jobs command to see which jobs are there and how they are numbered:

jobs
[1]- Stopped vim
[2]+ Stopped top

When looking at the jobs command output, there are three designations a job can have:

Image A plus sign (+) next to it indicates the current job, and any commands such as fg or bg act on that job by default.

Image A minus sign (-) next to it indicates the previous job or the next-to-last job to be operated on.

Image Lack of a character indicates it’s just a regular job, and no actions are taken on it unless specified by job number.

7. Put the default job into foreground mode with the fg command.

8. The top command should come to the foreground.

9. Quit the top command by pressing Q.

10. Run the jobs command again and notice that the vim job is now the current job again.

11. Kill the vim job by typing its ID with the kill command:

kill %1
Vim: Caught deadly signal TERM
Vim: Finished.

12. Run the jobs command again; you see the results of your action as reported by the Job Control function. In this case, job # 1 is terminated.

Image


Note

Be prepared to answer a question on the exam about what command or characters might put a process into the background or foreground a process listed in the jobs command output. You should also know what the jobs command + symbol indicates.


Managing Process Priorities

Linux uses a combination of priority and scheduling to run multiple processes in what appears to be multitasking on a single processor. On multiple processors, this makes for actual multitasking.

Strangely enough, the process priorities are backward, like a lot of other things, and they stretch from the highest (-20) to the lowest (19) (see Figure 7-3).

Image

Figure 7-3 Linux process priorities

Image

A process’s default priority is normally 0 when started, unless the programmer needs to set the starting priority higher. Although users can start a process with a lower (from 0 to 19) priority, only the root user can start a process with a higher (0 to -20) priority.

Many a sysadmin has discovered too late what it means to have multiple programs running at too high a priority. Too many processes with high priorities can slow a machine drastically, cause it to become unresponsive, and even cause crashes.

There are two main methods to specify or alter a process’s priority: at program start and while it’s running.

To start a program with a lower priority (the default), use the nice command, such as

nice kitty.sh

This causes the kitty.sh script to run at a priority of 10. The nice utility makes programs play nice with others, relieving some of the stress of running multiple processor or I/O-intensive programs.

You can also specify a priority using the -n option followed by the increment you want to alter the default priority by, such as

nice -n 10 kitty.sh

To change a process’s priority while it’s running, you use the renice program, such as shown here:

ps aux | grep mybigcompile
rbrunson 14729 19.2 0.6 1656 524/pts/0 R 01:30 mybigcompile
renice +5 14729

This command string causes the process mybigcompile (process ID 14729) to run at an altered priority of +5. When using the renice utility, there isn’t a default priority—one must be specified.

Image


Note

A regular user can only change an existing process to a lower priority, that is, a higher number. Only the root user can change a process’s priority to any value.


The other option for altering a running program’s priority is a feature of the top command. The top command shows a refreshing screen of processes with the highest CPU usage, configurable to show only active processes or a specific number of processes (see Figure 7-4).

Image

Figure 7-4 The top command

top reads its configuration from /etc/toprc or .toprc, where it can be restricted for use by users, removing some of the dangerous features. top runs interactively by default, refreshing every 5 seconds.

To make top do some fun things, try these:

Image top d 1—Runs and refreshes every 1 sec.

Image top i—Shows only active processes, may be toggled on and off

Some of the interactive (inside top) options you can use are

Image space—Updates the display immediately.

Image h—Provides help for top.

Image k—Kills a process; a prompt appears for the PID.

Image i—Either displays or ignores zombie/idle processes.

Image n—Is prompted for the number of processes to display.

Image r—Prompts for the PID to affect and then provides the new priority.


Note

You can sort the output of the top command by pressing the R key to sort the PIDs from high to low, a reverse sort. You can also invoke top with the -o option and specify a sort field to show sorted on that field immediately.


Finally, you can use the top command as a “fire and forget” command to send the current top output to you via email using the following command:

top -b -n 1 | mail root@yourserver.xxx -s "Top output from Server 1"

This command runs top in its batch mode (-b) one iteration or time (-n 1) and sends the output not to the console, but to the email address indicated with the subject line (-s) indicated. Try this on your local system and then check system mail by running mail. You’ll see the subject line for the email and you can read the output.

Leaving Programs Running after Logout

A common problem exists when you are a systems administrator who runs commands on the command line on servers that don’t have a GUI desktop or component: How do you log out and leave for a minute/hour/day and let a command or utility continue to run?

Related and similar is the question: How can you leave a command line session and go get a cup of coffee or tea or otherwise use the facilities without leaving your root user session hanging out and vulnerable?

There is a utility that shares a name, or part of a name, with the SIGHUP signal. It’s the nohup command, and it’s designed to be used in front of a command that you want to continue running even after the controlling tty or console has been exited. Think of it as setting a balloon free into a hangar or warehouse. The balloon represents the process to set free, and the building represents your machine’s memory space.

Image

Using this utility lets you run the command and then log out, as follows.

nohup somecommand

Alternatively, you can (and should!) use the screen utility, described in the next section.

Using screen for Multiple Console Sessions

I first began to use screen many years ago. I was a lab manager and was building a set of test systems. Part of the process was to download an entire repository consisting of a number of Gigabytes of packages for use in my lab, and it was taking all day. By 6:00 p.m. it was only three-fourths of the way done. I happened to have an important commitment that wouldn’t let me stay late and wait for the download process to finish, and I had heard about this command. I spent about half an hour learning about it, stopped the download, began the download all over again using thescreen command/utility, and by the next morning, everything was downloaded and working.

Image

The screen command is a text-based window or session manager that runs multiple shell sessions independently of each other, all within a simple-to-use text interface with minimal indication that it’s running on screen normally.

screen enables a number of handy features for the busy sysadmin:

Image Multiple independent sessions

Image Ability to use those windows/sessions for local or remote systems

Image Cut and paste of text between all the running windows/sessions

Image Ability to detach or “abandon” a window (complete with running program[s]), so you can log out, lock the screen, or otherwise go home

Image Scrollback history buffer on a per window/session basis

Image Automatic output logging for sessions that run and for which you want to see forensics on the output later

Without a utility such as screen, you would either have to stay around, use a graphical window manager and lock the screen, or leave the session open on a system that’s unattended, none of which is an elegant or safe solution.


Note

The screen command is typically installed on systems, but if it’s not available, just add it either through your RPM installation or apt-get installation routine.


Once installed, invoking screen is as simple as typing its name, but screen provides a lot of interesting options and capabilities, so let’s hit the highlights in the next section.

Image

Taking Control-a of screen Windows

Just about everything in screen begins with the pressing of the keys Ctrl and a. There are numerous options, which you can see on the help screen, reached by pressing Ctrl+a then ?, as shown in Figure 7-5.

Image

Figure 7-5 screen help options

Creating Windows in screen

A new “window” is really a new instance of a console in screen, so when you create a window, you are just opening up another session of the shell, and you can then do whatever you want in that session: type commands, run programs, or anything else that the shell allows you to do.

To create a window in screen, press Ctrl+a and then press c, and you’ll suddenly be in a new session/window at a shell prompt.

Once in that session/window, start the top command for something that shows movement and stays running when you are off in other windows, such as

top


Note

Exam-takers should know the basic commands for screen, especially how to create a new window/session and run a command in it automatically, aka screen someprogram.


Now switch back to your previous or initial session/window by pressing Ctrl+a and then p, although since you only have two windows open, n or p in this instance takes you to the other window.

Now start a new session/window by typing Ctrl+a and then c and run strace top, which shows an ongoing trace of the system calls that this particular instance of the top command is conducting and keeps displaying output for you until you cancel the command.

At this point, you should have three sessions/windows to switch to and from, so practice using Ctrl+a, n or Ctrl+a, p to move forward and backward among the sessions/windows.

You can see a listing of the available windows by pressing Ctrl+a and then , or the double quotation mark. For example, this would return the following listing on your screen, and you could type the number of the window session you wanted, such as “0” or “1” or “2” and be taken directly there.

Detaching and Reattaching from screen

Opening up local instances of the console via screen is a common usage pattern, but screen really shines when you realize that you can detach a session from screen as a new process and it will keep running even if you log out.

Image

To detach a process, you can either perform the detaching on a running process in an existing window or start a window/process in detached mode.

Detaching a current window/process is done by changing to that window/session and pressing Ctrl-a and then d, which shows output similar to

System1:~ rossb$ screen localbash
[detached]

You can see the sessions that are currently detached and running by using the screen –ls command, which shows you output similar to the following:

There are screens on:

....................78229.Localbash (Detached)
....................78520.bashshell (Attached)
2 Sockets in /var/folders/d7/mgwnjgpx1wd6y7pg0jwzytx40000gr/T/.screen.

You then can directly and immediately reattach the (sole) detached session by typing:

screen -r

The window/session is back in the foreground now, the program running as if it never went away or was detached, and it has indeed been running properly all this time.

If there are multiple detached sessions, you can most easily reattach the session you want by specifying its PID, such as

screen –r 88229


Note

Knowing the main operations for the screen command is helpful both on the exam and in real life. You should know how to do what we’ve covered without any documentation, from doing it many times. For those who work in a production environment with systems that only support shell or nongraphical sessions (which is a vast majority), the screen command is helpful and should be a part of your working-day toolkit.


Locking Your Console via screen

Locking the screen sessions is the last item we need cover, and that’s pretty simple to do. Whenever you are signed on to the system and running screen and have a window/session active, you can simply press Ctrl+a then x to lock the screen.

Image

If you have set a password in the ~/.screenrc file, it is the one that you have to enter to restore access to the window/session; otherwise, the lock mechanism prompts you for a key or password. You have to enter that twice and then it reports that it’s locked.

Summary

In this chapter we cover a lot of ground, showing you how to manage processes, send signals to properly kill and remove those processes, and force a system service to reread its configuration files. We also show the basics of controlling your system’s jobs, managing the priorities of those jobs while they are running, and how to display and understand many pieces of information on the system.

Finally, we cover how to leave programs running after you log out or how to lock your system and leave processes running even if it’s a text-only system.

Exam Preparation Tasks

As mentioned in the section “How to Use This Book” in the Introduction, you have a few choices for exam preparation: the exercises here, Chapter 21, “Final Preparation,” and the practice exams on the DVD.

Review All Key Topics

Review the most important topics in this chapter, noted with the Key Topics icon in the outer margin of the page. Table 7-3 lists a reference of these key topics and the page numbers on which each is found.

Image

Image

Table 7-3 Key Topics for Chapter 7

Define Key Terms

Define the following key terms from this chapter and check your answers in the glossary:

process

job

PID

priority

signal

page

slab

block

cache

queue

session

console

window

Review Questions

The answers to these review questions are in Appendix A.

1. Which command shows you a frequently updated screen display of the running processes on your system?

a. threads

b. procinfo

c. mem

d. free

e. top

2. You execute a command that is supposed to end the execution of a process, and it is not successful. Which signal should you use with the kill command to guarantee the termination of the process?

a. 15

b. 23

c. 9

d. 18

e. 27

3. As the sysadmin of a heavily used terminal server, you suddenly notice that the same user is logged on to many different terminals executing similarly named processes and the count of these processes keeps rising rapidly.

Which command would allow you to both find all the problem processes and kill them based on the user, controlling the terminal as well as the process name?

a. pkill

b. pgrep

c. pgmnorm

d. pkmon

e. pkexec

4. The jobs command can only be used on systems that run in text mode or via the ssh command. It cannot be used in graphical terminal sessions such as gnome-terminal or xterm. True or False?

a. True

b. False

5. You have just executed the screen command and are at a bash prompt. After creating three new window sessions, you want to see a list of the available screen sessions. Which keystroke set would you use to show the list?

a. Ctrl+a show all

b. Ctrl+a “

c. Ctrl+a ls

d. Ctrl+a c

e. Ctrl+c r