UNIX process group, session and Job Control

Source: Internet
Author: User

 

1. Process Groups, sessions, and Terminals

(1). Each process belongs to a process group. A process group is a collection of one or more processes. Generally, it is associated with a group of jobs and can receive various signals from the same terminal. Each process group has a unique process group ID (an integer, which can also be stored in the pid_t type ).

# Include <unistd. h>

Pid_t getpgrp (void );

// Return value; ID of the process group that calls the process

Each process group has a leader process. the ID of the leader process is that the process group ID equals to the process ID. A leader process can create a process group and a process in the group. If only one process exists, the process exists, regardless of whether the leader process is terminated. The time interval from the process group creation to the time when the last process leaves becomes the lifetime of the Process Group. The last process in the process group can be terminated or transferred to another process group.

Process call setpgid (setsid can also be) can participate in an existing group or create a new process group

# Include <sys/types. h>

# Include <unistd. h>

Int setpgid (pid_t pid, pid_t pgid );

// Return: if the request succeeds, the value is 0, and the error value is-1.

This sets the pid process's process group ID to pgid. If the pid is 0, the caller's process ID is used. In addition, if the pgid is 0, the process ID specified by the pid is used as the process group ID. If the two parameters are equal, the process specified by the pid becomes the process group leader.

A process can only set process group I D for itself or its sub-processes. After its sub-process calls exec, it can no longer change the process group I D of the sub-process.

In most job control shells, this function is called after fork to enable the parent process to set the process group ID of its child processes, and then enable the child process to set its own process group ID. One of these calls is redundant, but this ensures that the parent and child processes enter the process group before further operations. Otherwise, a race condition is generated when any process is executed first.

(2). session is a collection of one or more Process Groups.

 

For example, in shell:

$ Proc1 | proc2 &

$ Proc3 | proc4

In this case, three process groups exist in the session, namely {session leader}, {proc1, proc2}, {proc3, proc4 }.

The process can call the setsid function to create a new dialog period.

# Include <sys/types. h>

# Include <unistd. h>

Pid_t setsid (void );

If the process that calls this function is not the leader of a process group, the function creates a new dialog period and the result is:

(A) This process becomes the first process of the new dialog period (session leader, where the first process is the process that creates the dialog period ). This process is the only process in the new dialog.

(B) the process becomes the leader process of a new process group. The new process group ID is the process ID of the calling process.

(C) This process has no control terminal. If this process has a control terminal before setsid is called, the connection is also released.

If the calling process is already the leader of a process group, this function returns an error. To ensure that the process is not in this situation, fork is usually called first, and then the parent process is terminated, while the child process continues. Because the child process inherits the process group ID of the parent process, and the process ID is newly allocated, the two cannot be equal, so this ensures that the child process is not the leader of a process group.

The dialog period and process group have some other features:

• A single control terminal (controlling terminal) can be provided during a conversation ). This is usually the terminal device on which we log on (terminal logon status) or Pseudo Terminal Device (network logon status ).

• The first process of establishing a connection with the control terminal is called the control process ).

• Several process groups in a dialog can be divided into one foreground process group and one or more background process groups ). The foreground process group receives the terminal input signal. In Shell, Job control is the control of the frontend and backend process groups, And the & or Ctrl + Z process groups are the background process groups.

• If a control terminal exists during a dialog period, it has a foreground process group, and other process groups are background process groups.

• Whenever you type the interrupt key (often DELETE or Ctrl-C) or return key (often Ctrl -\), this will cause the interruption signal or exit signal to all processes in the foreground process group.

• The terminal's hanging signal is sent to the control process (the first process in the conversation .)

• The system will automatically create a control terminal upon login.

How to assign a control terminal depends on implementation. When open is enabled, there are several options related to the control terminal: O_NOCTTY if the file to be opened is a terminal device, it will not be treated as a process control terminal.

Sometimes, the program interacts with the control terminal regardless of whether the standard input and standard output are reoriented. The method to ensure the program read/write control terminal is to open the file/dev/tty. In the kernel, this special file represents the control terminal. If the program does not have a control terminal, opening this device will fail.

Note: There is only one control terminal. Usually, the control terminal/dev/tty represents the control terminal of the Current shell, which is actually a connection pointing to the actual terminal device. The actual terminal device may be tty1, ttyS1, or pst/1.

(3). control terminals and Terminals

First, we will introduce two abstract concepts:

Tty (collectively referred to as a terminal device): tty is derived from Teletypes or teletypewriters. It originally refers to a telex typewriter, which reads and sends messages through a printer keyboard over a serial cable, later, this item was replaced by a keyboard and a display, so it is more appropriate to call it a terminal. A terminal is a type of terminal device. It has multiple types and generally uses tty for short.

Pty (Pseudo Terminal, virtual terminal): remote telnet to the host or xterm requires no terminal interaction.

In the special file directory/dev/of a Linux system device, there are generally the following types of special device files on the terminal:

1. Serial Port Terminal (/dev/ttySn) Serial Port Terminal (Serial Port Terminal) is a Terminal device connected by a computer Serial Port. The computer regards each serial port as a character device. For some time, these serial port devices are usually called terminal devices, because at that time they were used to connect terminals.

2. Pseudo Terminal (/dev/pty/) is a pair of logical Terminal devices (namely, master and slave devices, operations on the master will be reflected on the slave ). For example,/dev/ptyp3 and/dev/ttyp3 (or/dev/pty/m3 and/dev/pty/s3 in the device file system ). They are not directly related to physical devices. If a program regards ptyp3 (master device) as a serial port device, the read/write operations on the port are reflected in another ttyp3 (slave Device) corresponding to the logical terminal device. Ttyp3 is the logical device used by another program for read/write operations. Telnet host A communicates with the logon program of host A through A Pseudo Terminal.

3. control Terminal (/dev/tty) if the current process has a control Terminal (Controlling Terminal),/dev/tty is the device special file of the control Terminal of the current process. You can run the "ps-ax" command to check which control terminal the process is connected. For the shell you log on to,/dev/tty is your current control terminal and the device number is (5, 0 ). Run the "tty" command to check which actual terminal device it corresponds. /Dev/tty is similar to a connection to the actually used terminal device. The read and write operations on the current control terminal are all written to the current terminal device. For example, echo "hello">/dev/tty is displayed directly on the current terminal. Cat </dev/tty reads and outputs the input (row buffering) from the current terminal.

4. the console terminal (/dev/ttyn,/dev/Console) is usually called the console in Linux ). It simulates a Linux terminal (TERM = Linux), and some special files of the device are associated with it: tty0, tty1, tty2, and so on. When you log on to the console, tty1 is used. With Alt + [F1-F6] keys, we can switch to tty2, tty3 and so on. Tty1-tty6 is called virtual terminal, and tty0 is an alias of the current virtual terminal, the information generated by the system will be sent to the terminal (also called the console terminal ). Therefore, no matter which virtual terminal is being used, the system information will be sent to the console terminal. /Dev/console refers to the console, which is a device that interacts with the operating system. The system directly outputs some information to the console. Currently, users can log on to the console only in single-user mode.

5. virtual terminal (/dev/pts/n) in Xwindows mode. for example, if I use konsole in Kubuntu, It is a virtual terminal. Run the tty command to view/dev/pts/1.

6. For other types of Linux systems, there are many types of special files on terminal devices for many different character devices. For example,/dev/ttyIn terminal devices for ISDN devices.

(4). Several commonly used terminal-related commands

(A). In ubuntu and other releases, Ctrl + Alt + F1-F6 under the graphic interface is the terminal to open the tty1-6 (). Under tty1-6 these terminals the Alt1-6 is switching the terminal, Alt + F7 enters the graphical interface.

 

(B). You can use ps-t to view other terminal processes (these terminals are in the getty status when they are initially started. Because the tty1 terminal is not logged on, run getty. And no other process uses the tty1 terminal ):

$ Ps-t tty1

PID TTY TIME CMD

1524 tty1 00:00:00 getty

 

(C). You can use the shell tty command to identify the currently used terminal:

$ Tty

/Dev/pts/0

 

(D). stty-set tty, change and print terminal line settings

The $ stty-a command is used to check and modify the communication parameters of the current control terminal. UNIX provides an important control method for keyboard input and terminal output. You can use the stty command to set options for a specific terminal or communication line.

$ Stty tostop # [-] tostop STOP the background task that attempts to write data to the terminal. (SIGTTOU)

$ Echo "hello world" & # The process trying to output will be terminated

[1] 3063

$ Fg

Echo "hello world"

Hello world

 

$ Stty-tostop

$ Echo "hello world "&

[1] 3065

Hello world # The result of no STOP is output directly.

$ Jobs

[1] + echo "hello world"

For all options,-option_name is disabled, and option_name is enabled. Setting control terminals is also an important task in management.

 

(4) There is a need to notify the kernel of which process group is the foreground process group, so that the terminal device driver can understand where terminal input and terminal signals are sent.

# Include <termios. h>

# Include <unistd. h>

Int tcgetattr (int fd, struct termios * termios_p); // if the call succeeds, the Group ID of the foreground process associated with the terminal file descriptor fd is returned. If an error occurs,-1 is returned.

Int tcsetattr (int fd, int optional_actions, const struct termios * termios_p); // if the call succeeds, 0 is returned, and-1 is returned if an error occurs.

// Struct termios defines the ID fields related to Terminal 1. For example, the BREAK Key and verification are ignored.

Most applications do not directly call these two functions, which are usually called by the Job control shell.

 

 

2. Job Control

(1) You can start multiple jobs (Process Groups) on a terminal to control which jobs can access the terminal and which jobs are running in the background. Job control requires support in three forms:

(A). Supports shell for Job control.

(B) The Terminal Driver in the kernel must support job control.

(C). Support for certain job control signals must be provided.

Three special characters enable the Terminal Driver to generate signals and send them to the foreground process group. They are:

• Interrupt characters (usually DELETE or Ctrl-C) generate SIGINT.

• Exit characters (usually Ctrl-\) to generate SIGQUIT.

• Use Ctrl-Z to generate SIGTSTP.

(2). Shell does not support job control

For Shell that does not support job control, such as bsh, its command and its own process are in the same session and foreground process group. The processes that run commands (&) and pipeline commands in the background are still in the same process group as the Shell.

If a background process tries to remove the terminal, such as cat> temp &. When there is job control, the background job is placed in the background process group. If the background job is a local read control terminal, the signal SIGTTIN is generated. If the process does not redirect standard input, Shell automatically redirects the standard input to/dev/null. Read/dev/null generates an EOF for cat to read to the end of the file and ends normally. In addition, the pipeline execution structure is as follows:

<Figure>

(3). Shell supporting job control

$ Ps-o pid-o ppid-o sid-o pgid-o command

PID PPID SID PGID COMMAND

2074 2068 2074 2074/bin/bash

2580 2074 2074 2580 ps-o pid-o ppid-o sid-o pgid-o command

We can see that they have different pgids. For pipeline commands, they belong to the same process group:

$ Ps-o pid-o ppid-o sid-o pgid-o command | cat

PID PPID SID PGID COMMAND

2074 2068 2074 2074/bin/bash

2584 2074 2074 2584 ps-o pid-o ppid-o sid-o pgid-o command

2585 2074 2074 2584 cat

(4). SIGHUP Signal

SIGHUP will be sent to the corresponding process in the following three cases:

1. When the terminal is closed, the signal is sent to the first process of the session and the process submitted as a job (that is, the process submitted with the & symbol)

2. When the first process of the session exits, the signal is sent to each process in the foreground Process Group of the session.

3. If the parent process exits and the process becomes an orphan process group, and the process in the process group is in the stopped state (the SIGTSTP signal is received), SIGHUP is sent to every process in the process group.

The system processes the SIGHUP signal by default and terminates the process that receives the signal. Therefore, if the program does not capture the signal, the process will exit when it receives the signal.

If a controlling process exits, the system revokes further access to the controlling terminal and sends a SIGHUP signal to the foreground process group. if a process such as a job-control shell exits, each process group that it created will become an orphaned process group.

(5). bash job control command

(A). nohup: Use nohup to keep the program running in the background forever

Because many programs are not daemon processes, we want them to run in the background and are not affected by the SIGHUP signal (such as shell exit or terminal connection disconnection), use the nohup command.

$ Nohup sleep 100 &

$ Appending output to nohup. out # whether or not the command is redirected to the output terminal, the output will be appended to the nohup file in the current directory.

$ Ps-t pts/0

# You can see that the sleep 100 process terminal is pts/0.

$ Exit

Then open another terminal:

$ Tty

/Dev/pts/1

$ Ps-ef | grep sleep | grep-v grep

Luffy 4171 1 0 18:12? 00:00:00 sleep 100

# Query again in 100 seconds. The result is blank. The process Exits normally.

(B). Job Number % n: The Shell supporting job control can recognize the job process of the Job Number % +

For example:

$ Sleep 10 &

[1] 4294

$ % 1 # bring % 1 to front, same as fg % 1

Sleep 10

(C). $ fg puts the first job on the foreground. Fg % n

(D ). bg pauses a command in the background and continues execution. If there are multiple commands in the background, you can call out the selected command with bg % jobnumber, % jobnumber is the serial number (not pid) of the command being executed in the background found through the jobs command ).

(E). jobs

(F). ctrl + z or &

 

(6) run the process in the background in Linux

(A). nohup command: omitted

(B). setsid command. If our process is not a sub-process of the terminal that accepts the HUP signal, it will not be affected by the HUP signal. Setsid can help us do this. For more information about System Call setsid (), see the preceding section.

$ Setsid ping www.baidu.com

$ PING www.a.shifen.com (119.75.218.70) 56 (84) bytes of data.

64 bytes from 119.75.218.70: icmp_req = 1 ttl = 54 time = 1.88 MS

......

^ C

64 bytes from 119.75.218.70: icmp_req = 3 ttl = 54 time = 1.65 MS

64 bytes from 119.75.218.70: icmp_req = 4 ttl = 54 time = 1.92 MS

......

The output information is constantly displayed on this terminal. Because this process is no longer a Shell session, Ctrl + C cannot terminate this process. Even if the entire terminal is closed, the program continues to run.

Terminate it on another terminal:

$ Ps-e-o pid-o sid-o pgid-o command | grep ping | grep-v grep

4474 4474 4474 ping www.baidu.com

# We can see that sid = pid. Because it is

$ Kill-SIGKILL 4396

$ Ps-ef | grep ping | grep-v grep

The process is killed.

(C ).(&)

Subshell: one or more commands can be executed in the sub-shell if they are included in. Therefore, jobs executed in the sub-shell cannot be seen by jobs, and naturally no hup signal is received. For example:

$ (Ping www.baidu.com &)

(D). disown

For commands that have been submitted, use the Job Scheduling disown to achieve the goal:

Use disown-h jobspec to make a Job ignore the HUP signal.

Use disown-ah to make all jobs ignore the HUP signal.

Use disown-rh to ignore the HUP signal for running jobs.

# Cp-r testLargeFile largeFile &

[1] 4825

# Jobs

[1] + Running cp-I-r testLargeFile largeFile &

# Disown-h % 1

# Ps-ef | grep largeFile

Root 4825 968 1 00:00:00 pts/4 cp-I-r testLargeFile largeFile

Root 4853 968 0 00:00:00 pts/4 grep largeFile

# Logout

If you are running a program that has not been added to the background, you can ctrl + Z to stop the process, and then use bg % n to continue executing the job. Use disown to ignore the hup signal.

(E). screen terminal simulator. This is a simple introduction here.

The screen process tree is not started:

$ Ping www.baidu.com> ~ /Temp. output &

[1] 4962

$ Pstree-H 4962 # Highlight the specified process

Init-Restart-/usr/bin/termin-Restart-bash

│ Mongo── bash-mongo── ping

......

When the screen process tree is used

# Screen-r Urumchi

# Ping www.ibm.com &

[1] 9488

# Pstree-H 9488

Init-+-/usr/bin/termin-+-bash

|-Bash-+-ping

| '-Screen --- screen-+-bash

 

Reference:

APUE

Man

Stty uses a technical http://fanqiang.chinaunix.net/a1/b4/20020606/060200245.html

Linux terminal, console, tty, pty and other concepts http://news.newhua.com/news1program_language/2010/623/10623141048745773199BCF0CFH6AKB9930IGCFKHBH4IBE65IDFI07F.html

IBM library-Linux tips: several methods to make processes run reliably in the background http://www.ibm.com/developerworks/cn/linux/l-cn-nohup/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.