[英]Sending signal from parent to child and vice-versa
我正在嘗試練習信號並試圖實現以下目標
1)孩子和父母打印10個數字並將警棍傳遞給其他人
2)父母/孩子在這里等待通過sigsuspend
3)信號捕獲只是為了捕獲信號
4)殺死用於發送帶有相應進程ID的信號
但是輸出在競爭條件下受損,我看到一旦父級從子級控制獲得信號,就永遠不會交還給子級
我也希望信號能夠捕獲信號,但似乎沒有發生。
你能指出我做錯了什么嗎?
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
static volatile int count = 0;
void sighandler(int sig)
{
if (sig == SIGUSR1)
{
printf(" \n child sends parent signal - \n ");
}
if (sig == SIGUSR2)
{
printf("\n parent sends child signal - \n ");
}
}
int main(void)
{
//pid_t pid, cid;
sigset_t block_csignal, block_psignal, empty_signal;
struct sigaction ccatch, pcatch;
setbuf(stdout, NULL);
/* Creating signal set for suspending process till
it receives below signal */
sigfillset(&block_csignal);
sigdelset(&block_csignal, SIGUSR2);
sigfillset(&block_psignal);
sigdelset(&block_psignal, SIGUSR1);
/* Creating signal set for catching the signal
and changing signal disposition */
sigemptyset(&ccatch.sa_mask); /* ccatch for catching signal from parent */
ccatch.sa_flags = 0;
ccatch.sa_handler = sighandler;
sigemptyset(&pcatch.sa_mask); /* pcatch for catching signal from child */
pcatch.sa_flags = 0;
pcatch.sa_handler = sighandler;
sigaction(SIGUSR2, &ccatch, NULL); /* catch signal from parent for child */
sigaction(SIGUSR1, &pcatch, NULL); /* catch signal from child for parent */
switch(fork())
{
case -1:
printf("error in child creation \n ");
exit(-1);
case 0:
printf(" \n Control in hand of child \n ");
while(count < 50)
{
int temp = 0;
printf(" \n c count --- \n ");
while (temp < 10)
{
printf(" %d ", count);
temp++;
count++;
}
printf(" \n parent id in child process --- %d \n ", getppid());
kill(getppid(), SIGUSR1); /* send signal to parent */
sigsuspend(&block_csignal); /* wait till you get signal from parent */
}
exit(1);
default:
printf("\n Control in hand of parent \n ");
sigsuspend(&block_psignal); /*wait till you get signal from child*/
printf("\n Control back in hand of parent \n ");
while (count < 50)
{
int temp = 0;
printf(" \n p count --- \n ");
while (temp < 10)
{
printf(" %d ", count);
temp++;
count++;
}
kill(getpid(), SIGUSR2); /* send signal to child */
}
break;
}
printf("\n ");
return EXIT_SUCCESS;
}
為了將信號從父級發送到子級,您首先需要存儲子級的pid(它是成功派生的返回值)。 在父代代碼中,使用getpid()
返回當前正在運行的進程的ID,因此返回父代。
嘗試類似:
int cid = fork();
if(cid == 0) //child
if(cid > 0){ // parent
//...
kill(cid,...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.