我已通过1个信号和1个管道在 C 上写了PingPong,所以我需要将pid1
发送到son2
,将pid2
发送到{{1 }},其中son1
,pid1
是pid2
,son1
的小点。
但我看到这张照片:
son2
我有这段代码:
Waiting..
PID: 4021
Waiting..
它在SIGUSR1_hdl的son2中的#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
int pidN;
int pid = -1;
int fd[2];
int max;
void SIGUSR1_hdl(int sig)
{
// Set pid
if (pid == -1) {
printf("Waiting..\n");
fflush(stdout);
scanf("%d", &pid);
printf("PID: %d\n", pid);
fflush(stdout);
kill(pid, SIGUSR1);
signal(SIGUSR1, SIGUSR1_hdl);
return;
}
// Read x
..
}
int main(int argc, const char **argv)
{
signal(SIGUSR1, SIGUSR1_hdl);
sscanf(argv[1], "%d", &max);
pipe(fd);
dup2(fd[0], STDIN_FILENO);
close(fd[0]);
int pid1;
if (!(pid1 = fork())) {
pidN = 1;
for (;;) pause();
}
int pid2;
if (!(pid2 = fork())) {
pidN = 2;
for (;;) pause();
}
kill(pid1, SIGUSR1);
dprintf(fd[1], "%d\n%d\n%d\n", pid2, pid1, 1);
close(fd[1]);
wait(NULL);
wait(NULL);
return 0;
}
之前闲逛。我究竟做错了什么?
我无法通过fork继承scanf
。我只能通过我的频道(fd)发送它。
答案 0 :(得分:0)
主要问题(除了您使用的信号不安全功能之外)是,当stdin
连接到非终端输入时,它被充分缓冲。这意味着当您尝试从stdin
进行读取(scanf
就是这样做)时,它将尝试尽可能多地填充缓冲区。
这意味着单个子进程将读取所有您已写入管道的数据,而其他子进程则不留下任何数据,这当然会导致scanf
无限阻塞
您需要使用两个管道,每个子进程一个,或者在进程之间进行其他某种同步。