Linux异步回收子进程
fork 可以使用goto语句。以及异步回收子进程的方法:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <stdlib.h>
void handler(int run)
{
int status;
int pid = waitpid(-1, &status, WNOHANG);
if(WIFEXITED(status))
printf("The child %d exit with code %d\n", pid, WEXITSTATUS(status));
}
int main()
{
pid_t fork_pid;
signal(SIGCHLD, handler);
fork_pid = fork();
if(fork_pid == 0)
goto child_position;
else
goto parent_position;
printf("nothing position\n");
parent_position:
sleep(10);
printf("this is parent! PID=%d\n", getpid());
return 0;
child_position:
printf("This is child! PID=%d\n", getpid());
return 1;
}
输出
This is child! PID=24610
The child 24610 exit with code 1
this is parent! PID=24609