c - 使用 sleep 函数时如何增加计数? (C语言)

标签 c signals sleep

嘿伙计们,我似乎迷路了。我应该能够在无限循环内增加子级中的计数,并在每次父级发送信号时打印计数(应该每 1 秒一次)。我编写了代码,但我认为使用 fork 后,子进程和父进程会同时运行,但事实并非如此,所以我不确定如何解决这个问题。任何帮助都会很棒

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
int count = 0;//global count variable

void catch(int signal){
printf("Ouch! - I got signal %d \n", signal);
printf("count is %d\n", count);
count = 0;
}

int main(){
int pid;
int sec=0;
pid = fork();
int count1 = 0;
(void) signal(SIGALRM, catch);
if(pid==-1){
    printf("error\n");
}
else if(pid==0){//if child
    while(1){//while loop to increment count while parent to sleeping
    count = count + 1;
    }
    //pause();

    }
else{//parent
    sleep(1);//1 second pause
    raise(SIGALRM);//send alarm
    count1 = count1 + 1;
    if(count1>=5){
        return 0;
    }
    exit(0);
}
return 0;

}

最佳答案

raise 将信号发送给您自己(即 parent )而不是 child 。使用kill(child_pid, SIGALRM)

关于c - 使用 sleep 函数时如何增加计数? (C语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10329498/

相关文章:

python - python中如何处理不同的信号

python - Python 上使用 time.sleep 的简单 websocket 服务器

c - 需要在 SIGCHLD 处理程序期间访问子进程的变量

c++ - SIGINT 信号在写入管道期间被丢弃

c - apache 对 update/var/www 文件夹的写入权限

C - While 循环未按字符串输入的预期退出

javascript - 如何在javascript for循环中的每次迭代后延迟?

java - 电梯寻找楼层模拟中的逻辑存在缺陷

c - 在 Xcode 上运行 C 程序时,出现错误 - 线程 1 : EXC_BAD_ACCESS (code=1, 地址=0x68)

c - 为什么对 c 代码的这种微小更改会导致执行时间出现如此巨大的差异?