c - 子进程的 SIGTSTP 信号处理程序

标签 c linux unix process signals

所以我正在尝试在子进程中为 SIGTSTP 信号实现信号处理程序。

基本上我想要实现的是:

  1. 启动子进程
  2. 让父进程等待子进程
  3. 在子进程上调用 Sleep x 秒。
  4. 在 sleep 结束执行之前,我想发送一个 Ctrl+Z 信号。 此信号应停止子进程,但恢复父进程 过程。然后父进程应该知道 停止进程。

我使用命令运行它:./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好像有点效果(但绝对不是我想要的!)

当我在子进程执行 sleep 的过程中按 ctrl+Z 键时,光标会继续闪烁剩余的时间(在我的例子中是 10 秒),但控制不会到达父进程。

在不按 ctrl+Z 的情况下,控制权会按预期返回到父级。

我做错了什么?

我也看到了这个答案,但是我不是很理解:

After suspending child process with SIGTSTP, shell not responding

最佳答案

你有两个进程:

  • 忽略信号的父级,

  • 设置处理程序的子进程,然后执行另一个进程 - 这将从内存中清除信号处理程序的代码(执行的程序将加载到调用进程的位置),因此也将清除信号设置也是如此。因此,您的信号处理函数将永远不会被调用。 Is it possible to signal handler to survive after “exec”?

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

  • 家长应该忽略这个信号,

  • child 应该保留默认的信号处理(这会停止它),

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

关于c - 子进程的 SIGTSTP 信号处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26371610/

相关文章:

php - 干预/图像需要 FileInfo

Linux查找同名文件复制到目标文件夹不覆盖

c++ - 解压缩文件的权限被拒绝 (popen)

bash - 将别名作为参数传递

c - 修改ELF文件

c - 多个源文件的一个标题?

c - 从已卸载模块的 pdb 中提取结构信息

linux - 在 Ubuntu 10.10 : problem with PATH 中安装 TexLive 2010

java - Java 中的 File.length() 返回错误的长度

c - 三角参数约简(约简模 2π)