[英]C Two child process sending signal to parent, parent replies
我在向 c 中的父進程發送多個信號時遇到問題。 我已經嘗試了很長時間,但最終還是陷入了死鎖或等待鎖。 但我認為它不應該那么復雜,我根本無法理解發生了什么......
所以我有一個父進程和兩個子進程。 孩子們向父母發出信號,它接受它們,然后向 pipe 中的孩子發送消息。 他們把它寫出來給控制台。
到目前為止我的代碼:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
void handler(int signumber) {
printf("Signal with number %i has arrived\n", signumber);
}
int main() {
signal(SIGUSR1, handler);
signal(SIGUSR2, handler);
int pipefd[2];
char sz[100];
if (pipe(pipefd) == -1)
{
perror("Pipe open error");
exit(EXIT_FAILURE);
}
pid_t child, child2;
child = fork();
if (child > 0)
{
pause();
printf("Signal1 arrived\n", SIGUSR1);
//pause();
printf("Signal2 arrived\n", SIGUSR2);
close(pipefd[0]); //Usually we close unused read end
write(pipefd[1], "Message", 13);
printf("Pipe write complete\n");
int status;
waitpid(child2, &status, 0);
waitpid(child, &status, 0);
printf("Parent process ended\n");
}
else
{
child2 = fork();
if(child2>0) //child 1
{
printf(" child 1 Waits 3 seconds, then send a SIGTERM %i signal\n", SIGUSR1);
sleep(3);
signal(SIGUSR1, handler);
close(pipefd[1]); //Usually we close the unused write end
printf("Child1 read start\n");
read(pipefd[0], sz, sizeof(sz)); // reading max 100 chars
printf("Child1 read end, Message: %s", sz);
printf("\n");
close(pipefd[0]); // finally we close the used read end
printf("Child1 process ended\n");
kill(child, SIGTERM);
}
else //child 2
{
printf("child 2 Waits 3 seconds, then send a SIGTERM %i signal\n", SIGUSR2);
sleep(3);
signal(SIGUSR2, handler);
close(pipefd[1]); //Usually we close the unused write end
printf("Child2 read start\n");
read(pipefd[0], sz, sizeof(sz)); // reading max 100 chars
printf("Child2 read end, Message: %s", sz);
printf("\n");
close(pipefd[0]); // finally we close the used read end
printf("Child2 process ended\n");
kill(child2, SIGTERM);
}
}
return 0;
}```
我認為您的代碼帶有競爭條件和 memory 錯誤。 您也沒有將SIGUSR1
或SIGUSR2
發送給父級。 主觀地說,您的解決方案以一種難以遵循的方式實施。 如果你以不同的方式排列你的陳述,我想你也會發現我看到的同樣的錯誤(我稍后會提到)。
我強烈建議從小處着手,朝着你的目標邁進。 例如,第 1 步可能是讓進程分叉,讓父進程通過 pipe 向子進程發送消息,讓子進程退出並讓父進程收割子進程。 在第 2 步中,僅將您在上面示例代碼中的信號處理程序添加到父級,並讓子級使用kill()
將該信號(父級將處理的確切信號)發送給父級。 在稍后的某個步驟中,添加另一個 fork 調用以創建另一個孩子。
就競爭條件而言,您的代碼是這樣排序的,這樣在第一次fork
之后,您有一個父進程將嘗試處理兩個子進程,但只創建了一個子進程。 因此,您正在嘗試做一些禁止的事情。 此外,第一個孩子正在創建第二個孩子。 這意味着第一個孩子的父母甚至不知道第二個孩子的存在,因為第一個孩子有一個完全不同的 memory 空間。 第一個孩子沒有等待它創建它的第二個孩子的waitpid
,因為它的“入口點”可以說是在代碼前面的waitpid
調用之后。
另外,請注意您的write(pipefd[1], "Message", 13);
很可怕。 write()
的最后一個參數是count
。 您提供了13
但字符串"Message"
的長度小於13
。 系統調用將向閱讀器吐出垃圾,導致更多不良問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.