【发布时间】:2015-03-02 17:20:05
【问题描述】:
我正在编写一个简单的 shell 程序,我可以在其中执行一些后台进程。我希望使用像“killbg”这样的特定命令能够对我执行的每个后台进程进行 SIGINT。我试过了:
- 使用
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
}
}
}
}
我做错了什么?
【问题讨论】:
-
你在子进程中设置
pgid,在父进程中对pgid执行kill(),父进程不知道子进程为pgid设置了什么。