【发布时间】:2017-12-15 10:46:25
【问题描述】:
这个程序是用 C 语言编写并在 ubuntu 上编译的。 我的脚本创建了两个孩子。 第一个在静态变量中记录他的 pid。 创建第二个孩子并向父母发送信号。
父母接收信号并在这一轮向第一个孩子发送信号。 但是第一个孩子没有收到这个信号。函数 sig_handlerr 永远不会被调用。
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
# include <sys/types.h>
# include <sys/wait.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <time.h>
# include <signal.h>
# include <sys/mman.h>
static pid_t* pidt;
// handler signal père
void sig_handler(int signo)
{
if (signo == SIGUSR1) {
printf("SIG HANDLER received SIGUSR1 by process %d\n", getpid());
printf("-> Envoie du signal SIGUSR1 au fils %d\n", pidt[0]);
// le père envoie un signal au premier fils
kill(pidt[0], SIGUSR1);
}
}
// handler signal fils
void sig_handlerr(int signo)
{
if (signo == SIGUSR1) {
printf("SIG HANDLER2 received SIGUSR1 by process %d\n", getpid());
}
}
int main(int argc, char* argv[]) {
printf("pid du processus père %d\n", getpid());
pidt = mmap(NULL, sizeof(pid_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (fork()==0) {
printf("1 processus fils %d\n", getpid());
pidt[0]=getpid();
printf("pid enregistré= %d\n", pidt[0]);
signal(SIGUSR1, sig_handlerr);
exit(0);
}
wait(NULL);
signal(SIGUSR1, sig_handler);
if (fork()==0) {
printf("2 processus fils %d", getpid());
// il envoie un signal SIGUSR1 au processsu père
printf("-> envoie SIGUSR1 au père %d\n", getppid());
kill(getppid(), SIGUSR1); // envoie un signal SIGUSR1 au processus père
exit(0);
}
wait(NULL);
printf("\n\n------ Fin du programme -------");
return EXIT_SUCCESS;
}
你能解释一下为什么吗?
【问题讨论】:
-
在我的机器上工作。 “SIG HANDLER 通过进程 21265 收到 SIGUSR1 -> Envoie du signal SIGUSR1 au fils 21266”,在信号处理程序中使用 printf 是未定义的行为。
-
你没有给第一个孩子发送任何信号
-
@Stargateur “Envoie du signal”消息仅表示父级尝试发送信号,而不是接收到。