转-10. Processes

From: http://www.win.tue.nl/~aeb/linux/lk/lk-10.html
Before looking at the Linux implementation, first a general Unix description of threads, processes, process groups and sessions.
A session contains a number of process groups, and a process group contains a number of processes, and a process contains a number of threads. (session:process group:process:thread,从左到右都是1:N的关系)
A session can have a controlling tty. (session:tty是1:1的关系)At most one process group in a session can be a foreground process group(前台pg只有1个). An interrupt character typed on a tty ("Teletype", i.e., terminal) causes a signal to be sent to all members of the foreground process group in the session (if any) that has that tty as controlling tty.(来自tty的signal将送给前台pg中的所有进程)
All these objects have numbers, and we have thread IDs, process IDs, process group IDs and session IDs.
10.1 Processes
Creation
A new process is traditionally started using the fork() system call: (进程是通过fork产生的)
pid_t p;
p = fork();
if (p == (pid_t) -1)
        /* ERROR */
else if (p == 0)   (pid=0 = 子进程)
        /* CHILD */
else
        /* PARENT */ (pid>0 = 父进程)
This creates a child as a duplicate of its parent. Parent and child are identical in almost all respects. In the code they are distinguished by the fact that the parent learns the process ID of its child, while fork() returns 0 in the child. (It can find the process ID of its parent using the getppid() system call.) (只能通过pid来区分,其他都是一样的)
Termination
Normal termination(正常终止) is when the process does
exit(n); or  return n;
from its main() procedure. It returns the single byte n to its parent.
Abnormal termination(异常终止) is usually caused by a signal(信号).
Collecting the exit code. Zombies
The parent does
pid_t p;
int status;
p = wait(&status);
and collects two bytes:
 
A process that has terminated but has not yet been waited for is a zombie(僵尸). It need only store these two bytes(2个字节): exit code and reason for termination.
On the other hand, if the parent dies first, init (process 1) inherits the child and becomes its parent.
Signals
Stopping (停止以后还可以继续)
Some signals cause a process to stop: SIGSTOP (stop!), SIGTSTP (stop from tty: probably ^Z was typed), SIGTTIN (tty input asked by background process), SIGTTOU (tty output sent by background process, and this was disallowed by stty tostop).
Apart from ^Z there also is ^Y. The former stops the process when it is typed, the latter stops it when it is read.
Signals generated by typing the corresponding character on some tty are sent to all processes that are in the foreground process group of the session that has that tty as controlling tty. (Details below.)
If a process is being traced, every signal will stop it.
Continuing
SIGCONT: continue a stopped process. (继续一个被停止的进程)
Terminating (终止)
SIGKILL (die! now!), SIGTERM (please, go away), SIGHUP (modem hangup), SIGINT (^C), SIGQUIT (^\), etc. Many signals have as default action to kill(默认是杀死) the target. (Sometimes with an additional core dump, when such is allowed by rlimit.) The signals SIGCHLD and SIGWINCH are ignored by default. All except SIGKILL and SIGSTOP can be caught or ignored or blocked. For details, see signal(7).
10.2 Process groups
Every process is member of a unique process group, identified by its process group ID. (When the process is created, it becomes a member of the process group of its parent./子进程会成为父进程所在进程组的成员) By convention, the process group ID of a process group equals the process ID of the first member of the process group, called the process group leader(进程组的ID=组头儿的ID=第一个进程的ID). A process finds the ID of its process group using the system call getpgrp(), or, equivalently, getpgid(0). One finds the process group ID of process p using getpgid(p).
One may use the command ps j to see PPID (parent process ID), PID (process ID), PGID (process group ID) and SID (session ID) of processes. With a shell that does not know about job control, like ash, each of its children will be in the same session and have the same process group as the shell. With a shell that knows about job control, like bash, the processes of one pipeline. like
% cat paper | ideal | pic | tbl | eqn | ditroff > out
form a single process group.
Creation
A process pid is put into the process group pgid by
setpgid(pid, pgid);
If pgid == pid or pgid == 0 then this creates a new process group with process group leader pid. Otherwise, this puts pid into the already existing process group pgid. A zero pid refers to the current process(pid=0是当前进程). The call setpgrp() is equivalent to setpgid(0,0).
Restrictions on setpgid()
The calling process must be pid itself, or its parent, and the parent can only do this before pid has done exec(), and only when both belong to the same session. It is an error if process pid is a session leader (and this call would change its pgid).
Typical sequence
p = fork();
if (p == (pid_t) -1) {
        /* ERROR */
} else if (p == 0) {    /* CHILD */
        setpgid(0, pgid);
        ...
} else {                /* PARENT */
        setpgid(p, pgid);
        ...
}
This ensures that regardless of whether parent or child is scheduled first, the process group setting is as expected by both.
Signalling and waiting
One can signal all members of a process group:
killpg(pgrp, sig);
One can wait for children in ones own process group:
waitpid(0, &status, ...);
or in a specified process group:
waitpid(-pgrp, &status, ...);
Foreground process group
Among the process groups in a session at most one can be the foreground process group of that session. The tty input and tty signals (signals generated by ^C, ^Z, etc.) go to processes in this foreground process group.
A process can determine the foreground process group in its session using tcgetpgrp(fd), where fd refers to its controlling tty. If there is none, this returns a random value larger than 1 that is not a process group ID.
A process can set the foreground process group in its session using tcsetpgrp(fd,pgrp), where fd refers to its controlling tty, and pgrp is a process group in the its session, and this session still is associated to the controlling tty of the calling process.
How does one get fd? By definition, /dev/tty refers to the controlling tty, entirely independent of redirects of standard input and output. (There is also the function ctermid() to get the name of the controlling terminal. On a POSIX standard system it will return /dev/tty.) Opening the name of the controlling tty gives a file descriptor fd.
Background process groups - 后台进程组。非前台,即后台
All process groups in a session that are not foreground process group are background process groups. Since the user at the keyboard is interacting with foreground processes, background processes should stay away from it. When a background process reads from the terminal it gets a SIGTTIN signal. Normally, that will stop it, the job control shell notices and tells the user, who can say fg to continue this background process as a foreground process, and then this process can read from the terminal. But if the background process ignores or blocks the SIGTTIN signal, or if its process group is orphaned (see below), then the read() returns an EIO error, and no signal is sent. (Indeed, the idea is to tell the process that reading from the terminal is not allowed right now. If it wouldn't see the signal, then it will see the error return.)
When a background process writes to the terminal, it may get a SIGTTOU signal. May: namely, when the flag that this must happen is set (it is off by default). One can set the flag by
% stty tostop
and clear it again by
% stty -tostop
and inspect it by
% stty -a
Again, if TOSTOP is set but the background process ignores or blocks the SIGTTOU signal, or if its process group is orphaned (see below), then the write() returns an EIO error, and no signal is sent.
Orphaned process groups - 孤儿进程组
The process group leader is the first member of the process group. It may terminate before the others, and then the process group is without leader.
A process group is called orphaned when the parent of every member is either in the process group or outside the session. In particular, the process group of the session leader is always orphaned.
If termination of a process causes a process group to become orphaned, and some member is stopped, then all are sent first SIGHUP and then SIGCONT.
The idea is that perhaps the parent of the process group leader is a job control shell. (In the same session but a different process group.) As long as this parent is alive, it can handle the stopping and starting of members in the process group. When it dies, there may be nobody to continue stopped processes. Therefore, these stopped processes are sent SIGHUP, so that they die unless they catch or ignore it, and then SIGCONT to continue them.
Note that the process group of the session leader is already orphaned, so no signals are sent when the session leader dies.
Note also that a process group can become orphaned in two ways by termination of a process: either it was a parent and not itself in the process group, or it was the last element of the process group with a parent outside but in the same session. Furthermore, that a process group can become orphaned other than by termination of a process, namely when some member is moved to a different process group.
10.3 Sessions
Every process group is in a unique session. (When the process is created, it becomes a member of the session of its parent.) By convention, the session ID of a session equals the process ID of the first member of the session, called the session leader(会话ID=会话头ID=第一个进程ID). A process finds the ID of its session using the system call getsid().
Every session may have a controlling tty, that then also is called the controlling tty of each of its member processes. A file descriptor for the controlling tty is obtained by opening /dev/tty. (And when that fails, there was no controlling tty.) Given a file descriptor for the controlling tty, one may obtain the SID using tcgetsid(fd).
A session is often set up by a login process(会话是通过登陆建立起来的). The terminal on which one is logged in then becomes the controlling tty of the session. All processes that are descendants of the login process will in general be members of the session.
Creation
A new session is created by pid = setsid(); //创建1个新的会话
This is allowed only when the current process is not a process group leader.(调用setsid的进程不能是组头儿) In order to be sure of that we fork first:
p = fork();
if (p) exit(0);
pid = setsid();
The result is that the current process (with process ID pid) becomes session leader of a new session with session ID pid. Moreover, it becomes process group leader of a new process group. Both session and process group contain only the single process pid(会话和pg只包含1个进程). Furthermore, this process has no controlling tty.
The restriction that the current process must not be a process group leader is needed: otherwise its PID serves as PGID of some existing process group and cannot be used as the PGID of a new process group.
Getting a controlling tty
How does one get a controlling terminal? Nobody knows, this is a great mystery(谜).
The System V approach is that the first tty opened by the process becomes its controlling tty.
The BSD approach is that one has to explicitly call
ioctl(fd, TIOCSCTTY, ...);
to get a controlling tty.
Linux tries to be compatible with both, as always, and this results in a very obscure complex of conditions. Roughly:
The TIOCSCTTY ioctl will give us a controlling tty, provided that (i) the current process is a session leader, and (ii) it does not yet have a controlling tty, and (iii) maybe the tty should not already control some other session; if it does it is an error if we aren't root, or we steal the tty if we are all-powerful.
Opening some terminal will give us a controlling tty, provided that (i) the current process is a session leader, and (ii) it does not yet have a controlling tty, and (iii) the tty does not already control some other session, and (iv) the open did not have the O_NOCTTY flag, and (v) the tty is not the foreground VT, and (vi) the tty is not the console, and (vii) maybe the tty should not be master or slave pty.
Getting rid of a controlling tty
If a process wants to continue as a daemon(守护进程), it must detach(拆卸) itself from its controlling tty. Above we saw that setsid() will remove the controlling tty. Also the ioctl TIOCNOTTY does this. Moreover, in order not to get a controlling tty again(再) as soon as it opens a tty, the process has to fork once more, to assure that it is not a session leader. Typical code fragment:
        if ((fork()) != 0)
                exit(0);
        setsid();
        if ((fork()) != 0)
                exit(0);
See also daemon(3).
Disconnect
If the terminal goes away by modem hangup, and the line was not local, then a SIGHUP is sent to the session leader. Any further reads from the gone terminal return EOF. (Or possibly -1 with errno set to EIO.)
If the terminal is the slave side of a pseudotty, and the master side is closed (for the last time), then a SIGHUP is sent to the foreground process group of the slave side.
When the session leader dies, a SIGHUP is sent to all processes in the foreground process group. Moreover, the terminal stops being the controlling terminal of this session (so that it can become the controlling terminal of another session).
Thus, if the terminal goes away and the session leader is a job control shell, then it can handle things for its descendants, e.g. by sending them again a SIGHUP. If on the other hand the session leader is an innocent process that does not catch SIGHUP, it will die, and all foreground processes get a SIGHUP.
10.4 Threads //线程是通过clone产生的
A process can have several threads. New threads (with the same PID as the parent thread) are started using the clone system call using the CLONE_THREAD flag. Threads are distinguished by a thread ID (TID). An ordinary process has a single thread with TID equal to PID. The system call gettid() returns the TID. The system call tkill() sends a signal to a single thread.
Example: a process with two threads. Both only print PID and TID and exit. (Linux 2.4.19 or later.)
% cat << EOF > gettid-demo.c
#include <unistd.h>
#include <sys/types.h>
#define CLONE_SIGHAND   0x00000800
#define CLONE_THREAD    0x00010000
#include <linux/unistd.h>
#include <errno.h>
_syscall0(pid_t,gettid)
int thread(void *p) {
        printf("thread: %d %d\n", gettid(), getpid());
}
main() {
        unsigned char stack[4096];
        int i;
        i = clone(thread, stack+2048, CLONE_THREAD | CLONE_SIGHAND, NULL);
        if (i == -1)
                perror("clone");
        else
                printf("clone returns %d\n", i);
        printf("parent: %d %d\n", gettid(), getpid());
}
EOF
% cc -o gettid-demo gettid-demo.c
% ./gettid-demo
clone returns 21826
parent: 21825 21825
thread: 21826 21825
%

--------------------------------------
DAEMON(3)                     Linux Programmer's Manual                     DAEMON(3)

NAME         top
       daemon - run in the background

SYNOPSIS         top
       #include <unistd.h>

       int daemon(int nochdir, int noclose);

   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

       daemon(): _BSD_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)

DESCRIPTION         top
       The daemon() function is for programs wishing to detach themselves from the controlling terminal and run in the background as system daemons. //脱离控制台,并且在后台运行
       If nochdir is zero, daemon() changes the calling process's current working directory to the root directory ("/"); otherwise, the current working directory is left unchanged. //进程的当前工作目录
       If noclose is zero, daemon() redirects standard input, standard output and standard error to /dev/null; otherwise, no changes are made to these file descriptors. //进程的标准I/O

RETURN VALUE         top
       (This function forks, and if the fork(2) succeeds, the parent calls _exit(2), so that further errors are seen by the child only.)  On success daemon() returns zero.  If an error occurs, daemon() returns -1 and sets errno to any of the errors specified for the fork(2) and setsid(2).

CONFORMING TO         top
       Not in POSIX.1-2001.  A similar function appears on the BSDs.  The daemon() function first appeared in 4.4BSD.

NOTES         top
       The glibc implementation can also return -1 when /dev/null exists but is not a character device with the expected major and minor numbers.  In this case
       errno need not be set.

SEE ALSO         top
       fork(2), setsid(2)

COLOPHON         top
       This page is part of release 3.32 of the Linux man-pages project.  A description of the project, and information about reporting bugs, can be found at http://www.kernel.org/doc/man-pages/.

GNU                                   2009-12-05                            DAEMON(3)

 

你可能感兴趣的:(转-10. Processes)