0
点赞
收藏
分享

微信扫一扫

利用sigaction回收多个子进程

德州spark 2022-02-14 阅读 62

SIGCHLD触发sigaction,进入回调函数,回收子进程

#include <stdio.h>
#include <ctype.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <signal.h>
#include <assert.h>
#include <sys/time.h>

void sig_catch(int signo){
	pid_t wid;
	int stat;
	while((wid = waitpid(-1, &stat, 0)) != -1){//循环回收,防止僵尸进程
		if(WIFEXITED(stat)){
			printf("wait : %d child\n", wid);
		}
	}
}

int main(int argc, char *argv[])
{
	struct sigaction act;
	act.sa_handler = sig_catch;  //回调函数
	sigemptyset(&(act.sa_mask)); //回调时的屏蔽字
	act.sa_flags = 0;            //默认屏蔽触发act的信号
	
	sigaction(SIGCHLD, &act, NULL);
	
	int i;
	for(i = 0; i < 10; ++i){
		if(fork() == 0){
			break;
		}
	}
	if(i == 10){
		sleep(1);
		printf("Daddy done\n");
	} else{
		printf("%d child done\n", getpid());
	}
	return 0;
}

在这里插入图片描述

举报

相关推荐

0 条评论