c - C中的信号()函数无法正常工作
问题描述
(下面的代码和输出)这是一个创建 2 个子进程的程序,向每个子进程发送信号以基本上定期打印 2 个不同的消息。程序使用 kill() 函数成功发送信号,但是当子进程收到信号时,他们没有执行他们应该做的事情。这是代码:
#include <stdio.h>
#include <unistd.h>
#include<stdlib.h>
#include <sys/types.h>
#include <stdbool.h>
#include<wait.h>
#include<string.h>
#include<signal.h>
void passage(int);
void AB(int);
//void BA(int);
bool ab = false;
bool ba = true;
int pid[2];
int I = 1;
void passage(int signum) //handler
{
printf("car %d passed.\n", i);
i++;
if(ab == false)
{
printf("light1: RED | light2: GREEN\n");
} else
{
printf("light1: GREEN | feu2: RED\n");
}
}
void AB(int sig)
{
printf("this message doesn't print out1.\n");
ab = !ab;
}
/*void BA(int sig)
{
// changer les rols des fils
printf("this message doesn't print out2.\n");
ba = !ba;
}*/
int main()
{
struct sigaction action;
action.sa_handler = passage;
sigaction(SIGALRM,&action,NULL);
pid[0]=fork();
if(pid[0] != -1 )
{
if (pid[0]==0)
{
// Code of child 1
printf("test1\n");
signal(SIGUSR1,AB);
exit(1);
} else
{
pid[1]=fork();
if(pid[1]==0)
{
// Code of child 2
printf("test2\n");
//signal(SIGUSR2,BA);
exit(2);
} else
{
// parent precessus
//send signals to the two childs after 3s
printf("PONT OUVERT\n");
while(1)
{
//sending signal to child 1 function to execute AB() each 3s
kill(pid[0],SIGUSR1);
//kill(pid[1],SIGUSR2);
alarm(3);
pause();
while ( wait(NULL) != -1 );
}
}
}
}
}
我是否声明了 ab bool 变量错误?输出仅每隔 3 秒反复打印第一个条件消息,ab 变量没有改变,它是“假的”。请问我错过了什么?我真的很感谢你的帮助。 在此处输入图像描述
解决方案
推荐阅读
- javascript - 请求超时???如何使用 routerlink 导航到 3 个页面
- java - 在java中比较/获取2个具有相同键但顺序不同的json文件?
- javascript - Gravity Forms Datepicker - 限制天数 - 代码仅在按下提交后有效?
- apache - AxisFault:从某些客户端(例如 Docuware)调用时出现命名空间不匹配错误
- unity3d - OnMouseDown 事件在相机视口外收到,其中对象不可见
- python - “int”对象没有属性“uniform”
- angular - 如何将幻灯片添加到引导轮播
- vba - 如何使用用户窗体上的按钮来清除内容控制框的内容
- php - Laravel - 将请求重定向到外部 url 并将其响应作为响应返回
- r - 不确定如何使用反应值