首页 > 解决方案 > 如何在linux中的子进程和父进程之间发送信号

问题描述

我有两个 cod,第一个是给父母的,它向SIGUSER1孩子发送信号 (),当孩子收到它时,他应该打印出他收到了它。

父代码

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>

void sighand(int);
int main()
{
    int cpid, ppid;
    ppid = getpid();
    printf("My process ID is %d\n", ppid);

    FILE *fp1;
    fp1 = fopen("cpid.txt", "w+");

    cpid = fork();

    if ( cpid == 0 ) {
        printf("I am the child  => PID = %d\n", getpid());
    }
    else
        printf("I am the parent => PID = %d, child ID = %d\n", getpid(), cpid);

    fprintf(fp1, "%d\n", cpid);
    // kill(cpid, SIGUSR1);//id, signal, send
    sigset(SIGUSR2, sighand);

    return 0;
}  

void sighand(int the_sig){
    if (the_sig == SIGUSR2){
        printf("sigusr2 received");
        exit(1);
    }
}

子代码

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>

void sighand1(int);
int main()
{
    FILE *fp1;
    int pid;
    fp1 = fopen("cpid.txt", "r");
    fscanf(fp1, "%d,", &pid);

    sigset(SIGUSR1,sighand1);

    while(1) {
        printf("Waiting..");
        sigpause(SIGUSR1);
    }

    return 0;
}

void sighand1(int the_sig)
{
    if (the_sig == SIGUSR1){
        printf("sigusr1 received");
        exit(1);
    }
}

当我启动代码时,它会打印出进程(子进程)已创建,然后当我发送信号时,它不会做任何事情,孩子会陷入循环或等待,而父母不会做任何事情,谁能告诉我我去了哪里我的代码或逻辑错误。

标签: clinuxubuntu

解决方案


您的代码有几个问题:

  • 您尝试通过文件传递一些 pid,但您可以使用该getppid()函数(获取父 ID)
  • 你有一些子代码,但它没有被调用
  • 没有信号发射

所以你的代码可以这样更正:

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

void parent_handler(int the_sig)
{
    if (the_sig == SIGUSR2){
        printf("sigusr2 received in parent\n");            
    }
}

void child_handler(int the_sig)
{
    if (the_sig == SIGUSR1){
        printf("sigusr1 received in child\n");
        kill(getppid(), SIGUSR2);
        exit(1);
    }
}

int child_function()
{
    /* prepare to receive signal */
    sigset(SIGUSR1,child_handler);

    while(1) {
        printf("Waiting..");
        fflush(stdout);
        /* wait for signal */
        sigpause(SIGUSR1);
    }

    return 0;
}

int main()
{
    int cpid, ppid;
    ppid = getpid();
    printf("My process ID is %d\n", ppid);

    cpid = fork();

    if ( cpid == 0 ) {
        printf("I am the child  => PID = %d\n", getpid());
        child_function();
        return 0;
    }
    else
        printf("I am the parent => PID = %d, child ID = %d\n", getpid(), cpid);

    /* child will never reach this point */
    sleep(1);

    /* prepare parent to received signal */
    sigset(SIGUSR2, parent_handler);

    /* send signal to child */
    kill(cpid, SIGUSR1);

    sleep(1);

    return 0;
}  

推荐阅读