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



我是UNIX的初学者。这几天我在上一门关于操作系统的课。在课堂材料中,有一个代码如下。

#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 Failedn");
exit(-1);
}
else if(pid==0){//child process
printf("I am the child %dn",pid);    //not working
execlp("/bin/ls","ls",NULL);
}
else{//parent process
//parent will wait for the child to complete
printf("I am the parent %dn",pid);   //not working
wait(NULL);
printf("Child Completen");
exit(0);
}
}

我预计这个程序的结果是(文件名为图3-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

我不知道为什么这个程序不产生("我是孩子%d\n",pid(和("我就是家长%d\n"(

谢谢你的帮助

您可以按照下面的代码运行ok。请使用getpid((而不是pid(。man2获取此处的pidcenter链接描述

#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 Failedn");
exit(-1);
}
else if(pid==0){//child process
printf("I am the child %dn",getpid());    //not working
execlp("/bin/ls","ls",NULL);
}
else{//parent process
//parent will wait for the child to complete
printf("I am the parent %dn",getpid());   //not working
wait(NULL);
printf("Child Completen");
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

最新更新