簡體   English   中英

如何通過kill命令從子進程向父進程發送信號

[英]How to send a signal from the child process to parent process through kill command

我試圖通過fork()系統調用創建一個子進程,然后嘗試將信號發送給父進程並在屏幕上打印出一些內容。

這是我的代碼:

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

void func1(int signum) {
    if(signum == SIGUSR2) {
        printf("Received sig from child\n");
    }
}

int main() {
    signal(SIGUSR2, func1);

    int c = fork();
    if(c > 0) {
        printf("parent\n");
    }
    else if(c == -1) {
        printf("No child");
    }
    else {
        kill(getppid(), SIGUSR2);
        printf("child\n");
    }

}

當我執行程序時,我得到的是:

child
Segmentation fault (core dumped)

我是C語言系統調用的新手,不知道為什么會這樣,以及如何獲得所需的輸出,這將是所有三個printf語句的打印。 相同的任何幫助,將不勝感激。

您的代碼有許多小問題,並且肯定具有未定義的行為,即,您不能從信號處理程序中調用printf或其他異步信號不安全函數。 這是帶有修復程序的代碼(請參閱代碼中的注釋)。 應該可以按預期工作(沒有特定的打印語句順序),並查看此代碼是否仍然存在段錯誤。

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

void func1(int signum)
{
    /* write is asyc-signal-safe */
    write(1, "Received sig from child\n", sizeof "Received sig from child\n" - 1);
}

int main()
{
    signal(SIGUSR2, func1);

    /* fork returns a pid_t */
    pid_t c = fork();
    if(c > 0) {
        printf("parent\n");
        /* Wait for the child to exit; otherwise, you may not receive the signal */
        if (wait(NULL) == -1) {
            printf("wait(2) failed\n");
            exit(1);
        }
    } else if (c == -1) {
        printf("fork(2) error\n");
        exit(1);
    } else {
        if (kill(getppid(), SIGUSR2) == -1) {
            /* In case kill fails to send signal... */
            printf("kill(2) failed\n");
            exit(1);
        }
        printf("child\n");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM