【问题标题】:How do you increment a count while using the sleep function? (in C language)使用 sleep 功能时如何增加计数? (在 C 语言中)
【发布时间】:2012-04-26 08:10:09
【问题描述】:

大家好,我好像迷路了。我应该能够在无限循环内增加一个孩子的计数,并在每次父母发送信号时打印计数,这应该是每 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;

}

【问题讨论】:

标签: c signals sleep


【解决方案1】:

raise 将信号发送给您自己(即父母)而不是孩子。使用kill(child_pid, SIGALRM)

【讨论】:

    【解决方案2】:

    使用 fork 后,两个进程的变量位于不同的内存位置。所以当你在父进程中发出信号时,打印出来的是父进程的“count”变量。您可以在子进程的循环中打印“计数”以查看它的增加

    【讨论】:

      猜你喜欢
      • 2012-05-06
      • 2018-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 2020-07-18
      • 2020-04-11
      • 2016-05-06
      • 2021-10-04
      相关资源
      最近更新 更多