簡體   English   中英

如何將信號從父進程重定向到子進程?

[英]How to redirect signal to child process from parent process?

我試圖了解C中的進程。我現在想創建一個類似於shell的結構-在按Ctrl + CCtrl + Z之類的快捷方式后,它將殺死其所有子進程,但將保持活動狀態。 我的代碼如下所示:

#include <ctype.h>
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/signal.h>

pid_t pid;

void send_signal(int signum){
  kill(pid, signum);
}

void init_signals(){
  signal(SIGINT, send_signal);
  signal(SIGTSTP, send_signal);
}

int main(){
    init_signals();
    pid = fork();
  if(pid > 0){
    //Parent Process
    wait(NULL);
  } else {
    // Child Process
    while(1){
        usleep(300000);
    }   

  }

  return 0;
}

這里的問題是,當我按Ctrl + C時,父級將其重定向到子級並殺死它,但是當我按Ctrl + Z(即使子進程已停止)時,父級仍掛在wait(NULL) 對於如何解決這個問題,有任何的建議嗎?

您可以在此處檢查如何在C中使用wait 長話短說:

等待系統調用使進程進入睡眠狀態,並等待子進程結束。 然后,它使用子進程的退出代碼填充參數(如果參數不為NULL)。

在子進程結束之前不會發出wait信號,因此僅通過讓子進程進入睡眠狀態,就沒有理由繼續執行主進程。 如果您想要進行任何設置,以便在孩子也可以正常工作時(包括當孩子睡覺時)主進程仍然可以正常工作,則您不能等待孩子。

對於外殼也沒有意義-它始終在后台處於活動狀態。 相反,您需要在main上有更好的處理程序-例如在條件上等待。 這樣,當您讓孩子入睡時,您可以告知情況並繼續前進。

除了https://stackoverflow.com/a/49346549/5694959上的解決方案之外,我還想提出另一種解決方案,僅用於處理父進程的信號。這樣,父進程將執行信號處理程序並將對子進程執行默認操作處理。 使用waitpid()獲取child的狀態。

waitpid(pid,NULL,WUNTRACED);

現在,當子進程更改其狀態(即終止或停止)時,父級將恢復執行。

如下更新代碼:

#include <ctype.h>
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/signal.h>

pid_t pid;

void send_signal(int signum){
  kill(pid, signum);
}

void init_signals(){
  signal(SIGINT, send_signal);
  signal(SIGTSTP, send_signal);
}

int main(){

    pid = fork();
  if(pid > 0){
    //Parent Process
    init_signals();
    waitpid(pid, NULL, WUNTRACED);
    printf("I think this is what you are expecting...\n");
  } else {
    // Child Process
    while(1){
        usleep(300000);
    }   

  }

  return 0;
}

請記住,請確保在按下ctrl + cctrl + z之前,請確保父進程已處理信號,否則,也會對父進程執行信號的默認操作。

暫無
暫無

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

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