在linux系统中, fork系统调用用于新建一个进程。
进程退出相关
1. void exit(int status), 进程退出,并且返回status & 0377给父进程
2. int atexit (void (*function)(void));用于注册进程退出时要执行的动作,执行顺序与注册顺序相反。由编译器完成这项工作。
3. int on_exit (void (*function)(int, void *), void *arg);这个函数的行为是以atexit函数为基础的,不应该再使用。
进程在退出时会发送信号SIGCHLD到父进程,父进程可以通过接收这个信号以感知子进程的终止,同时也可以通过wait函数来等待进程终止。
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait (int *status);
wait函数中返回的status可以通过一系列的宏来判断子进程是怎么终止的:
#include <sys/wait.h>
int WIFEXITED (status);
int WIFSIGNALED (status);
int WIFSTOPPED (status);
int WIFCONTINUED (status);
int WEXITSTATUS (status);
int WTERMSIG (status);
int WSTOPSIG (status);
int WCOREDUMP (status);
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
int main (void)
{
int status;
pid_t pid;
if (!fork ())
return 1;
pid = wait (&status);
if (pid == −1)
perror ("wait");
printf ("pid=%d\n", pid);
if (WIFEXITED (status))
printf ("Normal termination with exit status=%d\n",
WEXITSTATUS (status));
if (WIFSIGNALED (status))
printf ("Killed by signal=%d%s\n",
WTERMSIG (status),
WCOREDUMP (status) ? " (dumped core)" : "");
if (WIFSTOPPED (status))
printf ("Stopped by signal=%d\n",
WSTOPSIG (status));
if (WIFCONTINUED (status))
printf ("Continued\n");
return 0;
}
另一个等待进程结束的函数是
#include <sys/types.h>
#include <sys/wait.h>
pid_t waitpid (pid_t pid, int *status, int options);
其中参数pid有以下四个语义
< −1
Wait for any child process whose process group ID is equal to the absolute value of
this value. For example, passing −500 waits for any process in process group 500.
小于-1是等待进程组ID为|pid|的所有进程终止
−1
Wait for any child process. This is the same behavior as wait().
-1是等待所有的子进程
0
Wait for any child process that belongs to the same process group as the calling
process.
等于0也是等待子进程,但这些子进程的进程组ID必须与该进程的进程组ID一样
> 0
Wait for any child process whose pid is exactly the value provided. For example,
passing 500 waits for the child process with pid 500.
大于0时,就是要等待进程ID为pid的进程,可以理解为这个版本的waitpid才是正常版本的。