如果在命令末尾找到“&”,我正在尝试模仿在后台运行进程的 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..并且让程序继续接受新命令,我调用该函数并将背景标志设置为 1,我希望它在后台运行进程,告诉我它已经创建了进程..然后提示接受下一个命令。