哥哥姐姐們,我寫了一個孤兒行程
程式運行的結果 卻是 這樣的

第一次,./a.out 父行程結束之后,便進入了命令列,而此時,子行程還沒有結束,便在命令列后面列印出了 子行程 的內容。
請問,是因為 init 行程是一個后臺行程,所以,linux 在檢測到** 父行程結束之后,便列印出 命令列了嗎?**
可是,我同學說,在他的 linux 中,沒有出現這個現象。

這是由于什么原因呢? 和虛擬機的內核數有關嗎?
以下為源代碼
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
int main(){
// 宣告:int pipe(int pipefd[2]);
int fd[2];
char buf[128];
if(pipe(fd) < 0 ){
printf("creat pipe failed \n");
exit -1;
}
// printf("it is ok \n");
int pid;
pid = fork(); // fork() 創建 一個行程
if( pid < 0){
printf("creat son failed\n");
}
else if(pid > 0){
printf("into father \n");
close(fd[0]);
write(fd[1],"write from father",strlen("write from father"));
// printf("write is over \n");
}
else{
printf("pid = %d, into son\n",pid);
close(fd[1]);
read(fd[0],buf,128);
printf("read from father : %s\n",buf);
}
return 0;
}
uj5u.com熱心網友回復:
我想,可能是你的系統處理慢了一點。你讓同學在child process(pid == 0)的處理中加入sleep(1),應該也會出現和你同樣的現象。command line什么時候拿回控制權?
shell本身是一個行程,
通過shell呼叫程式后,相當于shell是父行程,被呼叫程式是子行程;
當子行程結束后,控制權回到父行程;
但是,父行程只知道自己的子女,并不知道孫子輩。
假如shell的行程用A表示,a.out的行程用B表示,a.out產生的子行程用C表示,
那么,A知道B,并在B結束后,控制權回到A手中;
A不知道C,A不會等待C有沒有結束。
但如果我們想讓A等待B和C,也可以,呼叫wait(man 2)函式,比如
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include <sys/wait.h> // wait() requires this header file
int main()
{
int fd[2];
char buf[128] = {0};
if(pipe(fd) < 0 )
{
printf("creat pipe failed \n");
exit(-1);
}
int pid;
pid = fork();
if( pid < 0)
{
printf("creat son failed\n");
}
else if(pid > 0)
{
int status;
printf("pid = %d, into father\n", pid);
close(fd[0]);
write(fd[1], "write from father", strlen("write from father"));
wait(&status); // call wait in calling process
}
else
{
sleep(1); // no matter how long it sleeps
printf("pid = %d, into son\n", pid);
close(fd[1]);
read(fd[0],buf,128);
printf("read from father : %s\n", buf);
}
return 0;
}
最后,
如果B行程還沒有結束,C提前結束,并且B沒有wait(),
C的行程被標記為zombie,這樣并不好,因為zombie行程會占用內核的資源,多一個zombie就少一個可產生的行程,
但是如果B行程也結束了,zombie行程會過繼給init(pid=1)行程,init會自動呼叫wait()來結束zombie。
以上,conforming to kernel 2.6 and POSIX.1-2001
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/11295.html
標籤:應用程序開發區
