检查子进程的状态

标签 c linux unix fork

您好,我对 C 编程有点陌生。我有以下代码,基本上程序需要检查子进程的状态,父进程等待子进程终止,然后打印“子进程已终止”。但我尝试了 WNOHANG,但不知何故我的第二次检查不起作用/或者我无法停止子进程。有什么想法吗?提前致谢。

代码:

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    int pid;
    int ppid;
    int status;
    pid=vfork();
    pid_t return_pid = waitpid(pid, &status, WNOHANG);

    if (pid<0) {
        printf("\n Error ");
        exit(1);
    } else if (pid==0) {
        printf("\n Hello I am the child process ");
        printf("\n My pid is %d %d ",return_pid, getpid());
        exit(0);
    } else if (return_pid == pid) {
            printf("child is finished %d %d", return_pid, pid);
            exit(0);
    } else {
        printf("\n Hello I am the parent process %d %d", return_pid, pid);
        printf("\n My actual pid is %d %d \n ",return_pid, getpid());
        exit(1);
    }
}

最佳答案

我想知道您的 waitpid 是否在错误的位置。检查 man 2 wait 并阅读 pid 的参数代表什么

The pid parameter specifies the set of child processes for which to wait. If pid is -1, the call waits for any child process. If pid is 0, the call waits for any child process in the process group of the caller. If pid is greater than zero, the call waits for the process with process id pid. If pid is less than -1, the call waits for any process whose process group id equals the absolute value of pid.

对我来说,粗体文本表示 child 可能正在等待自己? vfork 的值将为 child 返回 0。

此外,WNOHANG 选项将导致 waitpid 在子进程未退出时立即返回,这意味着父进程不会等待子进程完成。如果子进程已经完成,那么它将返回子进程的 pid。

关于检查子进程的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42744767/

相关文章:

c - 函数在 EditBox winApit 中获取选中的文本

c++ - recv() 失败 : Bad file descriptor c++ Linux

linux -/proc/iomem 的内容

c - 子进程返回的函数是否可以在父进程中捕获

android - Gradle Exec 任务从命令行构建运行,但不从 Android 构建运行

c - 无法在 UDP 中发送完整句子

c++ - 删除 C 结构结尾填充的最佳做法是什么?

c - 经常使用的结构变量。为什么要保持领先地位?任何性能增益?

将字符数组复制到文本文件中

linux - 进程的显卡内存和虚拟地址空间