C语言 waitpid、WNOHANG 和 SIGCHLD 的示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7155810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:27:36 来源:igfitidea点击:
Example of waitpid, WNOHANG, and SIGCHLD
提问by michael
I need an example of waitpid, WNOHANGand SIGCHLDcombined in C, and how I can use them all with fore\background?
我需要一个waitpid,WNOHANG并SIGCHLD在 C 中组合的示例,以及如何将它们与前景\背景一起使用?
signal( SIGCHLD, SIG_IGN );
waitpid(child, status, 0);
回答by Ottavio Campana
Taken from http://voyager.deanza.edu/~perry/sigchld.html
取自http://voyager.deanza.edu/~perry/sigchld.html
#include <stdio.h> /************ Handling SIGCHLD!! ******************/
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h> /***** For waitpid. *****/
#include <setjmp.h> /***** For sigsetjmp and siglongjmp. *****/
sigjmp_buf env;
main()
{
pid_t pid;
int n = 20;
struct sigaction sa;
void delete_zombies(void);
sigfillset(&sa.sa_mask);
sa.sa_handler = delete_zombies;
sa.sa_flags = 0;
sigaction(SIGCHLD, &sa, NULL);
sigsetjmp(env, 1);
if ((pid = fork()) < 0)
{
perror("Bad fork!");
exit(1);
}
if (pid > 0) /***** Parent *****/
{
printf("Created child %ld\n", pid);
sleep(n -= 2);
kill(0, SIGKILL);
}
else /***** Child *****/
{
sleep(2);
exit(0); /****** Not necessary here but... ******/
}
}
void delete_zombies(void)
{
pid_t kidpid;
int status;
printf("Inside zombie deleter: ");
while ((kidpid = waitpid(-1, &status, WNOHANG)) > 0)
{
printf("Child %ld terminated\n", kidpid);
}
siglongjmp(env,1);
}

