我正在编写一个简单的 shell 程序,我可以在其中执行一些后台进程。我希望使用像“killbg”这样的特定命令能够对我执行的每个后台进程发出信号。我尝试过:
- 使用
setpgid(0,0)
创建仅包含后台进程的进程组 在子句中pid=fork()
是 0,即当我要执行子进程时。 - 我在
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/