gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:19:42 25 4
gpt4 key购买 nike

我正在编写一个简单的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com