c++ - 如何仅在 C 中将 SIGINT 发送到后台进程

标签 c++ c linux

我正在编写一个简单的 shell 程序,我可以在其中执行一些后台进程。我希望使用像“killbg”这样的特定命令能够对我执行的每个后台进程发出信号。我尝试过:

  1. 使用 setpgid(0,0) 创建仅包含后台进程的进程组 在子句中 pid=fork()是 0,即当我要执行子进程时。
  2. 我在 setpgid(0,0) 之后得到的进程组“pgid”语句,我在kill函数中使用,例如kill(pgid, 2) .

不幸的是,整个程序被中断,后台任务仍在运行。

相关代码如下:

while(1){
  fgets.. //user input for command

  // Kill background processes      
        if(strcmp(execArgs[0], "killbg") == 0){    //execArgs argument array for execve
            kill(pgid, 2); 
            perror("");
        }
        pid=fork();

        // Error in fork
        if(pid <= -1){
            perror("Error with fork.\n");
         exit(EXIT_FAILURE);
        }       
        // Child process
        else if(pid == 0){
            if(execBG == TRUE){    // execBG true If user wants to run command in background
                setpgid(0,0);
                pgid = getpgid(pid);
            }
            execve(execArgs[0], execArgs, NULL); 
            fprintf(stderr, "Not a valid command! Remember the full path.\n");  

        }
        // Parent process       
        else{
            if(execBG==FALSE){
                waitpid(-1, &status, NULL);
            }
            else{
                ;    // if background process, don't wait for the child
            }
        }               
    }  
}

我做错了什么?

最佳答案

只是猜测... 1)您是否确保您的主要流程是不同组的一部分? 2) 一旦您的 child 因 stdin/stdout/stderr 连接而死亡,您的 parent 可能会收到 SIGPIPE。 SIGPIPE 的默认信号操作是终止(参见 signal(7))。

关于c++ - 如何仅在 C 中将 SIGINT 发送到后台进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28815748/

相关文章:

c++ - malloc/free 用于调整数组大小

linux - 错误: gyp_chromium returned non-zero exit status 1

c++ - git分支实验

c++:使用模板将任何lambda包装在另一个lambda中

c - C 中的字符串提取

linux - 将用户输入读取为整数

node.js - Nodejs express 上传文件debian vps报错

c++ - QT setMouseTracking(true) 完全没有效果

c++ - 在 map 上打印 vector

c - 如何在 GTK 中获得锁定的最大化窗口?