【发布时间】:2016-01-19 20:58:36
【问题描述】:
我正在尝试编写基本的 shell 程序来管理后台进程的作业控制。我了解将进程发送到您调用fork() 的后台,但不要在父进程中等待。但是,我也知道您需要使用 WNOHANG 选项调用 waitpid() 以获取已完成执行的进程的状态。我的问题是何时以及如何在我的代码中调用 waitpid() 以了解孩子何时完成。到目前为止,我只是在后台执行一个进程:
for (;;) {
char buff[PATH_MAX + 1];
char *cwd = getcwd(buff, PATH_MAX + 1);
printf("%s/", cwd);
char *cmd = readline("shell>"); //This code just sets up a cmd prompt
if (strcmp(tokList[0], bgCmd) == 0) {
//If the user inputs 'bg' then run the command in the background parent
pid_t child_pid = fork();
if (child_pid == 0) {
execvp(bgTokList[0], bgTokList); // This array contains just the arguments to be executed
perror("execvp");
return -1;
} else {
//parent
}
}
}
【问题讨论】: