gpt4 book ai didi

c - 何时使用 waitpid() 来查找后台进程的状态

转载 作者:太空宇宙 更新时间:2023-11-04 02:38:08 25 4
gpt4 key购买 nike

我正在尝试编写基本的 shell 程序来管理后台进程的作业控制。我知道将进程发送到您调用 fork() 的后台,但不要在父进程中等待它。但是,我也知道您需要使用 WNOHANG 选项调用 waitpid() 以获取已完成执行的进程的状态。我的问题是何时以及如何在我的代码中调用 waitpid() 以便知道 child 何时完成。到目前为止,这是我在后台执行一个进程所拥有的:

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
}
}
}

最佳答案

当子进程完成时,父进程将收到信号 SIGCHLD。然后您的信号处理程序可以获取状态。

Using an existing example ,您可以根据自己的需要对其进行修改。

关于c - 何时使用 waitpid() 来查找后台进程的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34886808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com