【问题标题】:How to send a signal from parent to child process using C?如何使用 C 将信号从父进程发送到子进程?
【发布时间】:2020-03-19 09:21:08
【问题描述】:

我需要使用 C 中的 Linux 进程将 "Ping pong" 写入命令行(父打印 "Ping",它的子 - "pong"),但我不知道如何从父母向孩子发送信号。

#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;
}

【问题讨论】:

  • kill 函数向另一个进程发送信号

标签: c signals


【解决方案1】:

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

#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 时,我们无法预测哪个进程会先执行。根据调度算法,父进程或子进程都可以执行。

在上面的代码中,我们有两个场景:

场景 1: 如果子进程先执行,我将使用 SIGSTOP 停止/暂停子进程的执行。因此,当子执行暂停时,父进程将被安排并打印“Ping”消息。打印 ping 消息后,我向孩子发出 resume/CONTINUE 信号。现在孩子打印“Pong”

场景 2: 如果父母先执行,我让父母等到子进程停止。因为在父打印“ping”之前,上下文切换可能会突然发生,并且可能会打印子进程中的消息。所以为了避免我一直等到孩子进入停止状态。一旦孩子处于 STOPPED 状态,Parent 打印“ping”并将 RESUME 孩子和孩子打印“pong”。

希望你明白我的解释...

【讨论】:

  • 谢谢。我不知道 kill() 除了终止进程之外会做任何事情
【解决方案2】:

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

这里有一个入门教程

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多