gpt4 book ai didi

c - setitimer()调用是否被 child 继承

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:32:28 26 4
gpt4 key购买 nike

我正在编写代码 fork (3、5 的数字,...不定数)。我希望我的程序在指定的时间后结束( parent 可能首先杀死它的 child 然后自己可能通过调用 _exit 这也是 sig-safe)。我的意思是在信号处理程序中,我通过 kill() 杀死整个 child ,然后为所有 child 调用 waitpid(),因为两者都是异步信号安全函数。为此,我在 fork 之前使用了 setitimer(ITIMER_REAL, &timer, NULL

那么它是被 fork 的 child 继承的吗?

如果不是继承的,能给个出处吗?

如果是遗传的话,是不是所有的children在取完时间后也都结束了?另外,其实我不想要这个案子。

最佳答案

不继承。

POSIX spec for fork明确提到定时器不继承并且 XSI(timer_create/timer_settime)定时器被重置:

  • [XSI] [Option Start] Interval timers shall be reset in the child process. [Option End]
  • Per-process timers created by the parent shall not be inherited by the child process.

测试程序如:

#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <signal.h>
#include <string.h>
#include <sys/time.h>

void h(int Sig)
{
char pid[20];
sprintf(pid,"%d\n",(int)getpid());
(void)write(1,pid,strlen(pid));
}
int main()
{
if(0>sigaction(SIGALRM,&(struct sigaction){.sa_handler=h},0)) return perror("sigaction"),1;
if(0>setitimer(ITIMER_REAL, &(struct itimerval){.it_value.tv_sec=1},0)) return perror("setitimer"),1;
pid_t ch; if(0>(ch=fork())) return perror("fork"),1;
pause();
if(ch){
sleep(1);
kill(ch,SIGTERM);
}
_exit(0);
}

显示处理程序仅在父级中运行——它只打印一个 pid。

关于c - setitimer()调用是否被 child 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55746442/

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