叉子没有显示在母亲的孩子pid

The*_*rag 2 c unix fork

我刚刚开始使用Fork并让它理解它是如何工作的,通常是在母亲那边,当我打印变量时a我应该得到子进程ID但它给我零

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

void main(){

    int a;
    a=fork();
    if(a==0){
        printf("Child Process, pid= %d, mother id: %d", getpid(), getppid());
        exit(0);
    }else{
        wait(&a);
        printf("Mother Process, Child pid= %d, mother's pid= %d ", a, getpid());    

    }

}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ner 7

您的使用wait不正确.它的定义如下:

pid_t wait(int *stat_loc)
Run Code Online (Sandbox Code Playgroud)

所以,当你打电话给它时

wait(&a);
Run Code Online (Sandbox Code Playgroud)

你忽略了返回值,它将是子节点的PID,并替换子节点fork返回的子节点PID .

如果你printf在等待之前放置语句,你会看到a已经有了孩子的PID.wait正确调用然后重复输出应该给出相同的结果......虽然在下面的例子中我也包括了状态结果.

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

void main(){

    int a;
    a=fork();
    if(a==0){
        printf("Child Process, pid= %d, mother id: %d\n", getpid(), getppid());
        exit(0);
    }else{
        int status;
        printf("Mother Process, Child pid= %d, mother's pid= %d\n", a, getpid());    
        a=wait(&status);
        printf("Mother Process, Child pid= %d, mother's pid= %d, status = %d\n", a, getpid(), status);    

    }

}
Run Code Online (Sandbox Code Playgroud)