问题描述
我目前正在从事操作系统概论课程的课堂作业,我们被要求用 C 构建一个简单的命令解释器。 对于这个解释器,如果我们把 '&' 放在一个命令之前,我们会在后台执行它,如果我们把 ';' 放在我们通常的(在前台)执行它.我们正在使用fork和进程管理功能,所以当我们在父进程中时,如果我们输入';',我们只需等待子进程(执行命令,例如pwd),如果我们把 '&' 我们只是不等待,我们打破了我们现在所处的位置。
这是代码:
err = get_arguments(buf,n,arg,MAXARG); //if we type & sleep 5 we get the sleep 5 in the arg
id = fork();
switch (id){
case -1:
errore("fork");
break;
case 0: /* child process */
/* execute the command using execvp */
pid = getpid();
pid_parent = getppid();
if(buf[0] == '&') {
printf("-U------- Child: just created (PID %d - Parent PID: %d): Now executing'%s ...' in the background...\n",pid,pid_parent,arg[0]);
} else if(buf[0] == ';') {
printf("-U------- Umea naiz: sortu berria (PID %d - Parent PID: %d): orain '%s ...' exekutatzera aurreko planoan...\n",arg[0]);
}
execvp(arg[0],arg);
printf("-U------- Child (PID %d): i'm here only if an error has ocurred\n",pid);
errore("exec");
break;
default: /* parent */
pid_child = id;
pid = getpid();
printf("-G------- Parent (PID %d): child process '%s ...' (PID %d) started \n",arg[0],pid_child);
if(buf[0] == '&') { // if we want to execute in the background
break; //break and don't wait for the child to stop
} else if(buf[0] == ';') { // if it's in the foreground
/* wait until child finishes */
pid_finished = wait(&status);
if ( pid_finished != pid_child) {
errore("wait");
} else {
if (WIFEXITED(status)){ // get the return code
child_return_code = WEXITSTATUS(status);
printf("-G------- Parent (PID %d): a child process (PID %d) has finished with the %d return code\n",pid_finished,child_return_code);
}
};
}
break;
}
}
for (n = 0; n < BUFSIZE; n++) buf[n] = '\0';
write(1,"prompt$ ",9); //write the prompt again
当我写; pwd 例如,它显然很好用。但是,我希望父进程知道在后台执行的子进程何时完成。如果发生,打印它的 id 和返回码。
我不知道怎么做,因为当使用 execvp 时,它后面的代码只有在发生错误时才会执行。那么我如何知道这个子进程何时在后台完成?
非常感谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)