【发布时间】:2019-05-02 13:13:12
【问题描述】:
我在 C 上通过 1 个信号和 1 个管道编写了 PingPong,所以我需要将 pid1 发送到 son2 和 pid2 到 son1,其中 pid1, pid2 是 son1、son2 的 pid。
但我看到了这张照片:
Waiting..
PID: 4021
Waiting..
我有这个代码:
#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;
}
它在 SIGUSR1_hdl 的 son2 中的 scanf 之前挂出。我究竟做错了什么?
我不能通过叉子继承pids。我只能通过我的频道 (fd) 发送。
【问题讨论】:
-
fflush()、scanf()和printf()不保证是异步信号保存。不应从信号处理程序中调用它们。