如果在命令末尾找到"&",我试图模仿后台运行进程的bash功能.我有以下功能......我不认为它正在做我想做的事情
int execute(char* args[],int background,int *cstatus){
pid_t child;
pid_t ch; /*Pid of child returned by wait*/
if ((child = fork()) == 0){ /*Child Process*/
execvp(args[0],args);
fprintf(stderr, "RSI: %s: command not found\n",args[0]); /*If execvp failes*/
exit(1);
}else{ /*Parent process*/
if (child== (pid_t)(-1)) {
fprintf(stderr,"Fork failed\n"); exit(1);
}else{
if (background==0){ /*If not running in background..wait for process to finish*/
ch = wait(cstatus);
}else{
printf("%ld Started\n",(long)getpid());
/* printf("Parent: Child %ld exited with status = %ld\n", (long) ch, (long)cstatus);
*/ }}
}
return 0;
}
int wait_and_poll(int *cstatus){
pid_t status;
status = waitpid(-1,cstatus,WNOHANG);
if (status>0){
fprintf(stdout,"%ld Terminated.\n",(long) status);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果我只是运行"ls -l"它按预期工作..但如果我想在后台运行ls ..并让程序继续接受新命令我调用函数,后台标志设置为1,我希望它在后台运行该进程,告诉我它已创建进程..然后提示接受下一个命令.
我不认为waitpid(-1, &cstatus, WNOHANG);
你认为它做了什么.您需要检查其返回值.如果是> 0
,那就是退出的子进程的PID.如果是0
或者-1
,没有子进程改变了状态.
您可以waitpid(-1, &cstatus, WNOHANG);
在运行每个命令之前和/或之后调用.在循环中调用它以捕获多个子出口.
您还可以处理SIGCHILD.子进程退出后,您的进程将立即收到此信号,如果您想立即报告子进程终止,则无需等待用户输入.