我正在尝试在 C 中模拟后台和前台进程。这样做时,如果最后有一个“&”符号,我会避免在父进程中等待该子进程。我还将我执行的所有后台命令存储在一个列表中,并在它们完成后尝试将它们从列表中删除。但是在 ls -l& 的情况下,输出会立即显示,只需按 enter 即可终止进程。如果它与列表中的现有 pid 匹配,如何捕获该进程 ID 并从我的列表中删除。
pid = fork();
//Code to add pid into a list if it is a background process
//this is done by parent as pid is always 0 for child processes
if(pid == 0){
if(proc_state=='&'){
setsid();
}
// logic for creating command
int ret= execvp( subcomm[0], subcomm );
// handling error
}
//Parent will execute this
//Child will never come here if execvp executed successfully
if(proc_sate != '&'){
for(i=0; i < count_pipe+1; i++){
int ret = waitpid(0, &flag ,0);
// Code to remove procid from list if 'ret' matches with existing procid in the list.
}
}
//Here proc_state just determines whether it is background or foreground.It is just a character. count_pipe is just a
//variable holding number of pipes
希望我清楚。如有疑问请提出问题