【问题标题】:How can I use signal handlers to stop and resume a child process?如何使用信号处理程序来停止和恢复子进程?
【发布时间】:2021-09-02 11:17:05
【问题描述】:

我尝试使用信号处理函数停止和恢复子进程,我的代码如下,但是结果似乎没有达到我想要的,为什么?

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include<sys/wait.h>
#include <unistd.h>
#include <sys/types.h>

#define ERR_EXIT(m)                     \
        do                                              \
        {                                               \
                perror(m);                      \
                exit(EXIT_FAILURE);     \
        }while(0)

#define MAXLINE 100

pid_t global_pid = -1; // global

void stop(int signo) 
{
    printf("catch the signo: %d, which is the 0xcc interruption\n",signo); 

    kill(global_pid,SIGSTOP); 
    
    printf("resume child process\n");

    kill(global_pid,SIGCONT); 

}

int main()
{
    printf("before fork, pid = %d\n",getpid());

    
    signal(5,(void(*)(int))stop); 
    
    global_pid = fork(); 


    if(pid == -1) 
    {
        ERR_EXIT("fork error\n");
    }
        
    if(pid > 0)
    {
        
        printf("This is parent pid = % d child pid = %d\n",getpid(),pid);
        
        sleep(5); 
          
    }else if(pid == 0)
    {
        

        printf("This is child pid = %d parent pid = %d\n",getpid(),getppid());

        asm volatile("int3"); 

        printf("The child continued.\n");
                
    }
    
    return 0;
}

结果如下。子进程未成功恢复。谁能告诉我该怎么做?

分叉前,pid = 128943

这是父 pid = 128943 子 pid = 128944

这是子 pid = 128944 父 pid = 128943

catch the signo: 5, 即 0xcc 中断

[1]+ 已停止 **

【问题讨论】:

  • 您展示的代码不会构建,更不用说运行并产生任何输出。请确保您的minimal reproducible example 仅包含您所询问的问题。
  • 在信号处理程序中调用printf 是不安全的。
  • 为什么标记为 C++?它看起来很像 C。也许问题是,你为什么要像 C 一样编写 C++?
  • 哦,对不起。这是一个疏忽。

标签: c++ fork


【解决方案1】:

孩子捕捉到了信号。在子进程中,global_pid 为零,因此您将信号发送到进程组。

【讨论】:

  • 是的,我刚刚发现了这个问题。现在可以了。
猜你喜欢
  • 2021-09-09
  • 2021-11-06
  • 2016-03-07
  • 1970-01-01
  • 2014-12-09
  • 1970-01-01
  • 2013-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多