gpt4 book ai didi

c - waitpid、WNOHANG 和 SIGCHLD 示例

转载 作者:太空狗 更新时间:2023-10-29 16:54:04 27 4
gpt4 key购买 nike

我需要一个在 C 中组合使用 waitpidWNOHANGSIGCHLD 的示例,以及如何将它们全部用于 fore\background?

 signal( SIGCHLD, SIG_IGN );

waitpid(child, status, 0);

最佳答案

取自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);
}

关于c - waitpid、WNOHANG 和 SIGCHLD 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7155810/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com