如何使用 C 将信号从 parent 发送到 child 进程?

How to send a signal from parent to child process using C?

我需要使用 C 中的 Linux 进程将 "Ping pong" 写入命令行(parent 打印 "Ping ",其 child - "pong"),但我不知道如何将信号从 parent 发送到 child.

#include <stdio.h>
#include <signal.h>
#include <unistd.h>

void childSignalHandler(int signal) {
    puts("pong");
}

void parentSignalHandler(int signal) {
    puts("Ping ");
}

int main() {
    int pid = fork();
    if (pid < 0) {
        printf("error");
        return -1;
    }

    if (pid == 0) {
        signal(SIGUSR2, childSignalHandler);
    } else {
        signal(SIGUSR1, parentSignalHandler);
        raise(SIGUSR1);
    }
    return 0;
}

您正在寻找管道,本质上它们构成了两个进程之间的单向连接。将它们视为可用于解析信息的虚拟文件。

这是一个入门教程

https://www.geeksforgeeks.org/pipe-system-call/

以下是您的问题的有效解决方案。

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>


int main() {
    int pid = fork();
    if (pid < 0) {
        printf("error");
        return -1;
    }

    if (pid == 0) {
        raise(SIGSTOP); // Stopping the execution of child process
        printf(" Pong");
    } else {
        waitpid(pid, NULL, WUNTRACED); // Wait until the child execution is stopped
        printf("Ping"); 
        kill(pid, SIGCONT);  // resume child process
    }
    return 0;
}

解释:

当我们使用fork时,我们无法预测哪个进程会先执行。根据调度算法,可以执行 PARENT 个进程或 CHILD 个进程。

在上面的代码中,我们有两种情况:

场景一: 如果child先执行,我是stopping/pausing使用SIGSTOP的child执行。因此,当 child 执行暂停时,PARENT 进程将被调度并打印 "Ping" 消息。打印 ping 消息后,我将 resume/CONTINUE 信号发送给 child。现在 child 打印 "Pong"

场景二: 如果 parent 先执行,我会让 parent 等到 child 进程停止。因为在 parent 打印 "ping" 之前,可能会突然发生上下文切换,并且可能会打印 child 进程中的消息。因此,为了避免我一直等到 child 移至停止状态。一旦 child 处于 STOPPED 状态,Parent 打印 "ping" 并将恢复 child 和 child 打印 "pong".

希望你理解我的解释...