等待:
等待有阻塞等待和非阻塞等待。
我們用非阻塞等待來實現異步。
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,