繁体   English   中英

子进程的SIGTSTP信号处理程序

[英]SIGTSTP signal handler for child process

因此,我正在尝试在子进程中为SIGTSTP信号实现信号处理程序。

基本上我想要达到的是:

  1. 开始子进程
  2. 让父级等待子进程
  3. 在“子进程”上调用“睡眠”达x秒。
  4. 在睡眠完成执行之前,我想发送Ctrl + Z信号。 该信号应停止子进程,但恢复父进程。 然后,父进程应该知道已停止进程的进程ID。

我使用以下命令运行它:./testsig sleep 10

到目前为止,这是我的代码:

#include<stdlib.h>
#include<stdio.h>
#include<signal.h>
#include<string.h>



volatile sig_atomic_t last_proc_stopped;
volatile sig_atomic_t parent_proc_id;

 void handle_stp(int signum)
  {
    if(getpid()==parent_proc_id)
    {
        kill(parent_proc_id,SIGCONT);
        signal(SIGTSTP,handle_stp);
    }
    else
    {
        last_proc_stopped=getpid();
      kill(parent_proc_id,SIGCONT);
    }   
  }



  void main(int argc, char *argv[])
  {

    int childid=0,status;

    signal(SIGTSTP,SIG_IGN);

    parent_proc_id=getpid();


    childid=fork();

    if(childid>=0)
    {

      if(childid==0)//child
      {


        signal(SIGTSTP,handle_stp);
        strcpy(argv[0],argv[1]);
        strcpy(argv[1],argv[2]);
        argv[2]=NULL;
        printf("Passing %s %s %s\n",argv[0],argv[1],argv[2]);
        execvp(argv[0],argv);
      }

      else
      {
        wait(&status);

        printf("Last Proc Stopped:%d\n",last_proc_stopped);

      }
    }

    else
    {
      printf("fork failed\n");
    }
  }

目前,ctrl + Z似乎具有某种效果(但绝对不是我想要的效果!)

当我在执行睡眠的孩子中间按下ctrl + Z时,光标会继续闪烁剩余的时间(在我的情况下为10秒),但是控件没有到达父进程。

在不按Ctrl + Z的情况下,控件将按预期方式返回到父级。

我究竟做错了什么?

我也已经看到了这个答案,但是我真的不能理解它:

使用SIGTSTP挂起子进程后,shell没有响应

您有两个过程:

您可以做什么来实现自己的目标?

  • 父母应该忽略这个信号,

  • 子级应保留默认的信号处理功能(这将停止处理),

  • 父级应使用waitpid()来查看子进程是否已退出或已停止,并采取相应措施(这实际上是杀死已停止的子进程)。

暂无
暂无

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

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