我正在尝试模仿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;
}
如果我只运行"ls -l",它会按预期工作。但如果我想在后台运行"ls"并使程序继续接受新命令,我将设置background标志并调用该函数。我希望它在后台运行进程,并告诉我它已经创建了该进程,然后提示我接受下一个命令。
waitpid(-1, &cstatus, WNOHANG)
。这将提供您所需的所有信息。 - n. m.waitpid
完全正常工作,请参见pastebin。 - n. m.