我不知道为什么这个程序只打印 "Child Complete"(UNIX)

I don't know why this program only prints "Child Complete"(UNIX)

我是 UNIX 的初学者。这些天我正在学习关于操作系统的class。在讲座材料中有下面的代码。

#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<unistd.h>
int main()
int main()
{
    pid_t  pid;
    //for a child program
    pid=fork();

    if (pid<0){
            fprintf(stderr,"Fork Failed\n");
            exit(-1);
    }
    else if(pid==0){//child process

            printf("I am the child %d\n",pid);    //not working
            execlp("/bin/ls","ls",NULL);
    }
    else{//parent process
            //parent will wait for the child to complete
            printf("I am the parent %d\n",pid);   //not working
            wait(NULL);
            printf("Child Complete\n");
            exit(0);
    }
}

我预计这个程序的结果是(文件名是 fig3-9.c 执行文件是 a.out)

I am the child 0
a.out concurrent.c fig3-9.c, fig3-11.c
I am the parent (som value)
Child Complete

但实际结果低于

a.out concurrent.c fig3-9.c, fig3-11.c

Child Complete

我不知道为什么这个程序没有 prinf("I am the child %d\n",pid) and ("I am the parent %d\n")

感谢您的帮助

您可以 运行 如下 code.please 使用 getpid() 而不是 pid()。 man2 getpidenter link description here

#include<stdio.h>
#include<stdlib.h>
#include<wait.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
    pid_t  pid;
    //for a child program
    pid=fork();

    if (pid<0){
            fprintf(stderr,"Fork Failed\n");
            exit(-1);
    }
    else if(pid==0){//child process

            printf("I am the child %d\n",getpid());    //not working
            execlp("/bin/ls","ls",NULL);
    }
    else{//parent process
            //parent will wait for the child to complete
            printf("I am the parent %d\n",getpid());   //not working
            wait(NULL);
            printf("Child Complete\n");
            exit(0);
    }
}

运行 结果:

future@ubuntu:~/work/tmp$ ./a.out 
I am the parent 7383
I am the child 7384
a.out  reverse_slist.c  seg_ment.c  unix_fork_print.c
Child Complete