在我的父行程等待后,我試圖將 SIGUSR1 發送到我的子行程 child_b。但是,我的 sigusr1 處理程式沒有執行并在輸出末尾列印我的訊息“pong quitting”。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <signal.h>
int fd[2][2];
void sig_handler(int signum) {
if (signum == SIGUSR1) {
printf("pong quitting\n");
exit(1);
}
}
void f1() {
int x = 0;
close(fd[0][0]);
close(fd[1][1]);
while (x <= 100) {
printf("ping: %d\n", x);
x ;
if (write(fd[0][1], &x, sizeof(int)) < 0) {
printf("Error writing f1\n");
}
if (read(fd[1][0], &x, sizeof(int)) < 0) {
printf("Error reading f1\n");
}
}
close(fd[0][1]);
close(fd[1][0]);
}
void f2() {
int x = 0;
close(fd[0][1]);
close(fd[1][0]);
while (x <= 100) {
if (read(fd[0][0], &x, sizeof(int)) < 0) {
printf("Error reading f2\n");
}
if (x <= 100)
printf("pong: %d\n", x);
x ;
if (write(fd[1][1], &x, sizeof(int)) < 0) {
printf("Error writing f2\n");
}
}
close(fd[0][0]);
close(fd[1][1]);
}
int main(void) {
for (int i = 0; i < 2; i ) {
if (pipe(fd[i]) < 0) {
printf("Error opening pipe.\n");
return 1;
}
}
pid_t child_a = fork();
if (child_a < 0) {
printf("Error forking child_a.\n");
return 2;
}
if (child_a == 0) {
f1();
} else {
pid_t child_b = fork();
if (child_b < 0) {
printf("Error forking child_b.\n");
return 3;
}
if (child_b == 0) {
signal(SIGUSR1, sig_handler);
f2();
}
else {
waitpid(child_a, NULL, 0);
waitpid(child_b, NULL, 0);
kill(child_b, SIGUSR1);
}
}
return 0;
}
我試過讓父母和孩子都睡,以及重新安排等待和殺戮的順序;但是,我無法讓信號處理程式執行。任何幫助,將不勝感激。
uj5u.com熱心網友回復:
殺死之后wait從根本上來說是錯誤的:程式已經死了,你要么得到ESCHR要么kill無辜的無關行程。
如果你移動了waitbefore kill,那么問題child_b會很快完成兩個(嘗試在下面運行它strace -f,看到運行時child_b已經是一個僵尸kill)。添加一些sleep(a_lot);或pause();在末尾child_b會有所幫助。
if (child_b == 0) {
signal(SIGUSR1, sig_handler);
f2();
pause(); //
}
else {
waitpid(child_a, NULL, 0);
kill(child_b, SIGUSR1); //^
waitpid(child_b, NULL, 0); //v
}
為了增加異步信號安全,您還可以將處理程式更改為異步信號安全:
void sig_handler(int signum) {
char m[]="pong quitting\n";
write(1,m,sizeof(m)-1);
_exit(1);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/530477.html
標籤:C信号信号处理子进程
下一篇:可以將陣列引數宣告為常量嗎?
