在C中发送信号从孩子到父母。 “用户定义信号1:30”

问题描述 投票:-1回答:1

我是初学者,通过编写一个将用作信号处理程序的函数kill_parent_process来发信号和练习。

此函数将要求父项退出()(发送SIGKILL或其他方法)。我这样做是让孩子向父母和处理程序exit()发送信号。但我觉得这就是问题所在,因为当我退出时,我可能只是退出子进程。但是,看起来从未调用过处理程序。这是我的代码

void kill_parent_process(int code) {
    fprintf(stderr, "KIll the Parent\n");
    exit(1);
}

int main() {
    struct sigaction sa;
    sa.sa_handler = kill_parent_process;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);

    int r = fork();

    if (r == 0) {


        sigaction(SIGUSR1, &sa, NULL);

        kill(getppid(), SIGUSR1);
        exit(1);
    } else if (r > 0) {

        while (1) {
            sleep(1);
            printf("%d\n",getpid());
        }
        int status;
        wait(&status);
        if (WIFEXITED(status)) {
            int result = WEXITSTATUS(status);
            fprintf(stderr, "%d\n", result);
        }

      } 
    }

当我运行程序并且从未调用过kill_parent_process时,我收到消息用户定义信号1:30。这段代码有什么问题?

c signals
1个回答
0
投票

以下提议的代码:

  1. 执行所需的功能
  2. 干净利落地编译
  3. 记录为什么包含大多数头文件的原因
  4. 不会调用任何信号处理程序等,而是使用默认操作
  5. 正确检查并处理错误

现在建议的代码:

#include <stdio.h>   // perror(), puts()
#include <stdlib.h>  // exit(), EXIT_FAILURE, EXIT_SUCCESS
#include <sys/types.h>  // for 'kill()' and 'getppid()'
#include <signal.h>  // kill()
#include <unistd.h>  // getppid(), fork()

int main( void )
{
    pid_t pid = fork();

    if( pid < 0 )
    {
        perror( "fork failed" );
        exit( EXIT_FAILURE );
    }

    else if( pid == 0 )
    {  // then child
        puts( "in child process" );
        kill( getppid(), SIGUSR1 );
        exit( EXIT_SUCCESS );
    }

    else // if ( pid > 0 )
    { // then parent
        while(1)
        {
            puts( "in parent process" );
            sleep(1);
        }
    }
}

建议代码的(典型)输出是:

in parent process
in child process
User defined signal 1
© www.soinside.com 2019 - 2024. All rights reserved.