首页 > 解决方案 > 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 变量没有改变,它是“假的”。请问我错过了什么?我真的很感谢你的帮助。 在此处输入图像描述

标签: clinuxterminalsignals

解决方案


推荐阅读