gpt4 book ai didi

c - 从 parent 向 child 发送信号,反之亦然

转载 作者:行者123 更新时间:2023-11-30 15:12:36 25 4
gpt4 key购买 nike

我正在尝试练习信号并尝试实现以下目标

1) child 和家长打印10个数字并将接力棒传递给其他人

2)父/子通过sigsuspend等待轮流

3) sigaction 只是为了捕获信号

4)kill用于发送带有各自进程ID的信号

然而,输出受到竞争条件的影响,我发现一旦父级从子级控件获得信号,就永远不会将其返回给子级

我还期望 sigaction 也能捕获信号,但这似乎没有发生。

你能指出我做错了什么吗?

#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(它是成功 fork 的返回值)。在父代码中,您使用 getpid() 来返回当前正在运行的进程的 ID,即父进程。

尝试如下:

  int cid = fork();
if(cid == 0) //child
if(cid > 0){ // parent
//...
kill(cid,...
}

关于c - 从 parent 向 child 发送信号,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34969849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com