【发布时间】:2020-10-06 19:03:45
【问题描述】:
这个无限程序创建了 2 个子进程,并在 while() 循环中设置了一个 3 秒的 alarm(),然后向两个子进程发送信号,以便它们打印出一些东西。当我执行时,代码的第一个循环有效,其中一个子进程打印了一些东西,但随后我在终端中收到“闹钟”中断,这是为什么? (最后检查一下while循环,我猜问题就在那里)。
#include <stdio.h>
#include <unistd.h>
#include<stdlib.h>
#include <sys/types.h>
#include <stdbool.h>
#include <sys/wait.h>
#include<string.h>
#include<signal.h>
void passage(int);
void AB(int);
void BA(int);
bool ab =false;
int pid[2];
int i =1;
void passage(int signum) //handler
{
printf("Voiture %d passée\n", i); i++; ab = !ab;
}
void AB(int sig)
{
if(ab == false)
{
printf("feu1: ROUGE | feu2: VERT\n"); ab = !ab;
}
}
void BA(int sig)
{
if(ab == true)
{
printf("feu1: VERT | feu2: ROUGE\n");
}
}
int main()
{
struct sigaction action;
action.sa_handler = passage;
sigaction(SIGALRM,&action,NULL);
int fd[2];
if(pipe(fd)==-1) { printf("pipe error"); return 1;}
pid[0]=fork();
if(pid[0] != -1 )
{
if (pid[0]==0)
{
close(fd[0]);
bool y;
read(fd[0], &y, sizeof(_Bool));
close(fd[0]);
// Code du child 1
printf("test1\n");
signal(SIGUSR1,AB);
while(1);
} else
{
pid[1]=fork();
if(pid[1]==0)
{
// Code child 2
printf("test2\n");
signal(SIGUSR2,BA);
while(1);
}else
{
// parent precessus
//send signals to the two childs after 3s
printf("PONT OUVERT\n");
close(fd[0]);
write(fd[1], &ab, sizeof(_Bool));
close(fd[1]);
while(1)
{
alarm(3);
pause();
kill(pid[0],SIGUSR1);
kill(pid[1],SIGUSR2);
}
while( wait(NULL) != -1); // gcc test.c -o test
}
}}
}
【问题讨论】:
-
This post 谈论
wait(NULL)的行为。 -
你
close(fd[0])紧接着是read(fd[0])。也许你有一个错字。
标签: c linux terminal signals interruption