您的位置:首页 > 其它

子进程的异步等待方式

2017-06-15 16:25 351 查看
等待:

等待有阻塞等待和非阻塞等待。

我们用非阻塞等待来实现异步。

1, 子进程终止时会给父进程发送SIGCHLD信号

2, 为了验证子进程在退出时确实向父进程发送了SIGCHLD信号,我们对SIGCHLD信号进行捕捉

3,

#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<signal.h>
#include<sys/types.h>
#include<unistd.h>
void handler(int child)
{
printf("i had revieve sigal");
}
int main ()
{
signal(SIGCHLD, handler);
pid_t id = fork();
if (id == 0)
{
printf("i am child\n");
sleep(2);
exit(-1);
}
while (1)
{
sleep(1);
printf("wait signal ...\n");
}

return 0;
}


4,



5, pid_t waitpid(pid_t pid, int *status, int options);

6,

pid = -1:等待任何一个子进程,与wait相同。

pid = 0:等待与调用者进程组id相同的任意子进程。

pid > 0:等待进程id与pid值相同的子进程。

pid < - 1:等待进程组id与pid绝对值相等的任意子进程。

7,参数option依具体值的不同含义:

WNOHANG:非阻塞式等待指定的进程。

WUNTRACED:如果子进程进入暂停执行则马上返回,但结束状态不予以例会。

WCONTINUED:若实现支持作业控制,那么由pid指定的任一子进程在暂停后已经继续,但状态尚未报告,则返回状态。

8,

#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<unistd.h>

void handler(int sig)
{
pid_t id;
while ((id = waitpid(-1, NULL, WNOHANG)) > 0)
{
printf("father wait success!\n");
}
printf("chiild is quit! %d\n", getpid());
}

int main()
{
signal(SIGCHLD, handler);
pid_t pid1 = fork();

if(pid1 == 0)
{
printf("i am child... one\n");
sleep(3);
exit(3);
}
pid_t pid2 = fork();
if(pid2 == 0)
{
printf("i am child... two\n");
sleep(2);
exit(2);
}

pid_t pid3 = fork();
if(pid3 == 0)
{
while(1)
{
sleep(1);
printf("i am three child, i am working!\n");
}
}

while (1)
{
sleep(1);
printf("father \n");
}
return 0;
}


9,

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  异步等待