小记——fork与进程

在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才是正常版本的。

当option参数为WNOHANG,并且指定的子进程的状态没有改变时,函数立刻返回,其返回值为0。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一尺丈量

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值