使用sleep函数时如何增加计数?(C语言)
嘿,伙计们,我好像迷路了。我应该能够在无限循环中增加子循环中的计数,并且在父循环每次发送信号时打印计数,应该是每1秒一次。我编写了我的代码,但我认为在使用fork之后,子进程和父进程同时运行,但是情况并非如此,因此我不确定如何解决这个问题。任何帮助都会很好使用sleep函数时如何增加计数?(C语言),c,signals,sleep,C,Signals,Sleep,嘿,伙计们,我好像迷路了。我应该能够在无限循环中增加子循环中的计数,并且在父循环每次发送信号时打印计数,应该是每1秒一次。我编写了我的代码,但我认为在使用fork之后,子进程和父进程同时运行,但是情况并非如此,因此我不确定如何解决这个问题。任何帮助都会很好 #include <stdio.h> #include <unistd.h> #include <signal.h> int count = 0;//global count variable void
#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;
#包括
#包括
#包括
整数计数=0//全局计数变量
无效捕捉(int信号){
printf(“哎哟!-我得到信号%d\n”,信号);
printf(“计数为%d\n”,计数);
计数=0;
}
int main(){
int-pid;
整数秒=0;
pid=fork();
int count1=0;
(无效)信号(信号灯、信号灯);
如果(pid==-1){
printf(“错误\n”);
}
else if(pid==0){//if子级
while(1){//while循环在父循环到睡眠时增加计数
计数=计数+1;
}
//暂停();
}
else{//parent
睡眠(1);//暂停1秒
升起(信号);//发出警报
count1=count1+1;
如果(计数1>=5){
返回0;
}
出口(0);
}
返回0;
}
raise
将信号发送给您自己(即家长),而不是孩子。使用kill(child\u pid,SIGALRM)
使用fork后,两个进程的变量位于不同的内存位置。因此,当您在父进程中发出信号时,输出的是父进程的“count”变量。您可以在子流程的循环中打印“计数”以查看其增加请使用编辑按钮对您的问题进行更改,不要再问基本相同的问题