2012-11-02 31 views
1

當我意識到我的程序沒有退出時,我在系統編程中練習管道。我在孩子和家長中都加了exit(),但孩子仍然沒有退出。請幫助... 下面是代碼:即使在調用exit()函數後,c中的進程也不會退出

所有的
#include<stdlib.h> 
#include<stdio.h> 
#include<unistd.h> 
//#include "apue.h" 

main() { 
     int n,max=20; 
     pid_t pid; 
     int fd[2]; 
     char line[max]; 
     int i; 
     for(i=0;i<20;i++) { 
      line[i]='\0'; 
     } 

     if(pipe(fd)<0) { 
      perror("pipe error"); 
     } 
     if((pid=fork())<0) { 
      perror("fork error"); 
     } 
     else if(pid > 0) { 
      close(fd[0]); 
      write(fd[1], "hello world\n", 12); 
      exit(1); 
     } else { 
      close(fd[1]); 
      read(fd[0], line, max); 
     } 
     puts(line); 
     exit(1); 
} 
+2

你怎麼知道它不會退出?你得到的行爲是什麼?你期望的是什麼? – 2012-11-02 20:05:10

+0

出口(0)是更好的... – 0x90

+2

好吧,出口(EXIT_FAILURE)是最好的,如果這是... – effeffe

回答

2

首先,fork函數返回0的孩子不是在parrent。所以,當你寫

否則,如果(PID> 0){

 close(fd[0]); 
     write(fd[1], "hello world\n", 12); 
     exit(1); } 

你是在parrent過程。要在子進程空間中,你應該使用else if(pid **==** 0)

你應該做的第二件事是確保一切正常,你不應該在子進程代碼空間調用函數exit()。你最好等待你的孩子進程在parrent進程中。爲此,您應該在parrent進程中使用wait()函數。

好的代碼如下:

main() { 
    int n,max=20; 
    pid_t pid; 
    int fd[2]; 
    char line[max]; 
    int i; 
    int status; 
    for(i=0;i<20;i++) { 
     line[i]='\0'; 
    } 
     if(pipe(fd)<0) { 
     perror("pipe error"); 
    } 
    pid=fork(); 
    if(pid <0) { 
     perror("fork error"); 
    } 
    else if(pid == 0) { // Here is the child process 
     close(fd[0]); 
     write(fd[1], "hello world\n", 12); 
     **// Do not kill child process because is dangeorus to do this when you use pipes** 
    } else { // Parrent process 
     close(fd[1]); 
     read(fd[0], line, max); 
     puts(line); 

     wait(&status);  // Wait the child process to end its job 

    } 

    return 0; 

}

+0

這些upvotes是什麼?我還沒有看到,OP在哪裏混淆了父母和孩子。來源中沒有「殺人」,完全可以退出孩子。順便說一句,'return 0'不會做其他任何事情。 –

+0

他說> else if(pid> 0){ close(fd [0]); write(fd [1],「hello world \ n」,12); exit(1); 我以爲他想要在孩子的過程和他比較pid的方式,這意味着他是在parrent過程中。其次,你認爲exit(1)的含義是什麼?它意味着退出與錯誤代碼和子進程將被殺害;) –

+0

我不會混淆孩子和父進程之間,我只是希望這兩個進程結束後,他們的工作,即 父母寫入管道,並讓孩子從中讀取並顯示 – Haris

相關問題