gpt4 book ai didi

c - 如何在没有外部机制的情况下通信树的进程

转载 作者:行者123 更新时间:2023-11-30 16:52:24 24 4
gpt4 key购买 nike

我需要使用 fork() 在 C 中构建具有以下形状的进程树:

Process tree

我必须在它们之间发送信号,所以我还想知道是否有任何方法可以将进程的 PID 存储在数组或其他内容中,这样每个进程都有其他进程的 PID。问题是我有一些限制,例如不使用管道、文件或其他外部机制在进程之间共享数据。 sleep和exec都不能使用。

这就是我在它们之间发送信号的方式:

Signal directions

最佳答案

So I just have to create them in a certain order so at the moment they are created, the PID of the process they will send a signal is already created?

对 - 特别是 H4 必须在 H3/N3 之前 fork ,以便 N3 知道 H4。演示:

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

void handler(int signum, siginfo_t *si, void *u)
{
printf("%d received signal from %d %s\n", getpid(), si->si_pid,
si->si_value.sival_ptr);
}

main()
{
// for demo, defer signal delivery until process unmasks the signal
sigset_t set, oldset;
sigemptyset(&set);
sigaddset(&set, SIGRTMIN);
sigprocmask(SIG_BLOCK, &set, &oldset);

sigaction(SIGRTMIN, &(struct sigaction){ .sa_sigaction = handler,
.sa_flags = SA_SIGINFO }, NULL);
pid_t P = getpid();
pid_t H1 = fork(); if (H1 < 0) perror("H1"), exit(1);
if (H1 == 0)
{
// use sigqueue() instead of kill(), so can pass sender ID
sigqueue(P, SIGRTMIN, (union sigval){.sival_ptr = "H1"});
sigsuspend(&oldset);
exit(0);
}
pid_t H2 = fork(); if (H2 < 0) perror("H2"), exit(1);
if (H2 == 0)
{
pid_t N2 = fork(); if (N2 < 0) perror("N2"), exit(1);
if (N2 == 0)
{
sigqueue(H1, SIGRTMIN, (union sigval){.sival_ptr = "N2"});
sigsuspend(&oldset);
exit(0);
}
sigqueue(N2, SIGRTMIN, (union sigval){.sival_ptr = "H2"});
sigsuspend(&oldset);
exit(0);
}
sigqueue(H2, SIGRTMIN, (union sigval){.sival_ptr = "P"});
pid_t H4 = fork(); if (H4 < 0) perror("H4"), exit(1);
if (H4 == 0)
{
sigqueue(P, SIGRTMIN, (union sigval){.sival_ptr = "H4"});
sigsuspend(&oldset);
exit(0);
}
pid_t H3 = fork(); if (H3 < 0) perror("H3"), exit(1);
if (H3 == 0)
{
pid_t N3 = fork(); if (N3 < 0) perror("N3"), exit(1);
if (N3 == 0)
{
sigqueue(H4, SIGRTMIN, (union sigval){.sival_ptr = "N3"});
sigsuspend(&oldset);
exit(0);
}
sigqueue(N3, SIGRTMIN, (union sigval){.sival_ptr = "H3"});
sigsuspend(&oldset);
exit(0);
}
sigqueue(H3, SIGRTMIN, (union sigval){.sival_ptr = "P"});
sigprocmask(SIG_UNBLOCK, &set, NULL);
do ; while (wait(NULL) > 0 || errno != ECHILD);
}

示例输出:

1074 received signal from 1072 P1072 received signal from 1073 H11072 received signal from 1076 H41075 received signal from 1074 H21073 received signal from 1075 N21077 received signal from 1072 P1076 received signal from 1078 N31078 received signal from 1077 H3

关于c - 如何在没有外部机制的情况下通信树的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41244286/

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