繁体   English   中英

使用信号处理程序暂停/恢复子进程

[英]Using Signal Handlers to Pause/Resume a Child Process

我目前正在尝试通过使用C中的信号来控制用fork()方法创建的子进程来对C中的信号进行实验。 本质上,我有一个子进程从linux终端运行“ yes”命令(此命令仅显示“ y”和换行符,直到终止)。 我希望能够使用CTRL-Z暂停/恢复此过程。 这就是我现在得到的:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
pid_t CHILD_PROCESS;
pid_t PARENT_PROCESS;
int isPaused;
void pause_handler(int signo){
  if(!isPaused){  
    printf("Ctrl-Z pressed. Pausing child.\n");
    isPaused = 1;
    kill(CHILD_PROCESS,SIGSTOP);
  }
  else if(isPaused){
   printf("\nCtrl-Z pressed. Resuming child.\n");
   kill(CHILD_PROCESS,SIGCONT);
   isPaused = 0;
  }
}

int main(int argc, char** argv){
  pid_t pid;
  PARENT_PROCESS = getpid();
  pid = fork();
  if(pid == 0){
    system("yes");
  }
  isPaused = 0;
  if(pid > 0){
    signal(SIGTSTP, SIG_IGN);
    signal(SIGSTOP, SIG_IGN);
    CHILD_PROCESS = pid;
    while(1){
      if(signal(SIGTSTP,pause_handler) == SIG_ERR){
        printf("Signal Failure");
      }
    }
  }
}

运行此命令时,我可以得到“按下Ctrl-Z。暂停子项”。 通过按CTRL-Z打印到控制台,我可以得到“按Ctrl-Z。恢复子级”。 再次按CTRL-Z打印到控制台。 但是,它实际上并不会一遍又一遍地恢复打印“ y”。 关于子进程为何不恢复的任何想法?

事实证明, system有一个隐式fork调用,因此存储在CHILD_PROCESS的PID最终实际上不是子进程,而是中间进程。

man 3 system

   The  system()  library  function uses fork(2) to create a child process
   that executes the shell command specified in command using execl(3)  as
   follows:

       execl("/bin/sh", "sh", "-c", command, (char *) 0);

   system() returns after the command has been completed.

因此,如果我们用execl("/bin/sh", "sh", "-c", "yes", NULL)替换system("yes")调用,则可以避免这种额外的派生,并且程序功能为期望。


唯一的其他问题是,根据我在这篇文章中发现的评论,在信号处理程序中使用printf是未定义的行为。 这里不是要担心的问题,但是将来的代码要牢记!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM