通过1个管道和1个信号进行PingPong:scanf在等待什么?

时间:2018-11-30 11:21:39

标签: c pipe signals fork

我已通过1个信号和1个管道在 C 上写了PingPong,所以我需要将pid1发送到son2,将pid2发送到{{1 }},其中son1pid1pid2son1的小点。

但我看到这张照片:

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)发送它。

1 个答案:

答案 0 :(得分:0)

主要问题(除了您使用的信号不安全功能之外)是,当stdin连接到非终端输入时,它被充分缓冲。这意味着当您尝试从stdin进行读取(scanf就是这样做)时,它将尝试尽可能多地填充缓冲区。

这意味着单个子进程将读取所有您已写入管道的数据,而其他子进程则不留下任何数据,这当然会导致scanf无限阻塞

您需要使用两个管道,每个子进程一个,或者在进程之间进行其他某种同步。