用于子进程的SIGTSTP信号处理程序

Roh*_*anC 5 c unix linux signals process

所以我试图在子进程中为SIGTSTP信号实现一个​​信号处理程序.

基本上我想要实现的是:

  1. 启动子进程
  2. 让父进程等待子进程
  3. 在子进程上调用Sleep,持续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");
    }
  }
Run Code Online (Sandbox Code Playgroud)

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

当我在执行睡眠的子项中间点击ctrl + Z时,光标继续闪烁(在我的情况下为10)秒,但控件没有到达父进程.

如果没有按ctrl + Z,控制将按预期返回到父级.

我究竟做错了什么?

我也看到了这个答案,但我真的无法理解它:

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

Las*_*lko 4

你有两个进程:

\n\n\n\n

你可以做什么来实现你的目标?

\n\n
    \n
  • 家长应忽略该信号,

  • \n
  • 孩子应该保留默认的信号处理(这会阻止它),

  • \n
  • 父进程应该用来waitpid()查看子进程是否退出或停止,并采取相应的行动(这涉及实际杀死已停止的子进程)。

  • \n
\n