首页 > 解决方案 > 如何使用信号处理程序来停止和恢复子进程?

问题描述

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

#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]+ 停止 **

标签: c++fork

解决方案


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


推荐阅读