如何将信号从父进程重定向到子进程? [英] How to redirect signal to child process from parent process?

查看:133
本文介绍了如何将信号从父进程重定向到子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解C语言中的进程.我现在想创建一个类似于shell的结构-在按 Ctrl + C Ctrl之类的快捷方式后 + Z 将杀死其所有子进程,但将保持活动状态.我的代码如下:

I am trying to understand processes in C. I currently want to create shell-like structure which - after pressing a shortcut like Ctrl+C or Ctrl+Z will kill all its subprocesses but will stay alive. My code looks like this:

#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)上.有关如何解决此问题的任何建议?

Problem here is that, when I press Ctrl+C, parent redirects it to child and kills it but when I press Ctrl+Z (even though child process is stopped) parent still hangs on wait(NULL). Any suggestions on how to fix this?

推荐答案

您可以在此处查看

You can check here how to use wait in C . Long story short:

wait系统调用使进程进入睡眠状态,并等待子进程结束.然后,它使用子进程的退出代码填充参数(如果参数不为NULL).

The wait system-call puts the process to sleep and waits for a child-process to end. It then fills in the argument with the exit code of the child-process (if the argument is not NULL).

在子进程结束之前,不会发出

wait信号,因此仅通过使子进程进入睡眠状态,就没有理由继续执行主进程.如果您想进行任何设置,以便在孩子也可以正常工作时(包括当孩子睡觉时)主进程仍然可以工作,那么您就不能等孩子了.

wait doesn't get signaled until the child process ends, so just by sending the child to sleep there is no reason for the main process to continue. If you want any setup where the main process still works while the child does as well (including when it sleeps!) you can't wait on the child.

对于外壳也没有意义-它始终在后台处于活动状态.相反,您需要在main上有更好的处理程序-例如在条件上等待.这样,当您让孩子入睡时,您可以告知情况并继续前进.

Wouldn't make sense for a shell either - it's always active in the background. Instead you need a better handler on main - like waiting on a condition. That way, when sending a child to sleep, you can signal the condition and keep going.

这篇关于如何将信号从父进程重定向到子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆