我是 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 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")
感謝您的幫助
uj5u.com熱心網友回復:
您可以按照以下代碼正常運行。請使用 getpid() 而不是 pid()。man2 getpid在此處輸入鏈接描述
#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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/461203.html
