2017-06-12 63 views
-1

我試圖在CentOS上使用datewc和管道。我不能printf,我在parentchild。任何幫助表示讚賞。Printf在叉子後未能在父級和子級中打印

#include <stdio.h> 
#include <pthread.h> 
#include <unistd.h> 
#include <assert.h> 
#include <time.h> 
#include <stdlib.h> 
#include <semaphore.h> 
#include <string.h> 
#include <stdlib.h> 
#include <fcntl.h> 

/* pipe1.c - send information through pipe. */ 

void syserr(char* msg) 
{ 
    printf("%s", msg); 
} 

void child(int pfd[]){ 
    dup2(pfd[1],1); 
    execl("/bin/date", "date", 0); 
} 

void main() 
{ 
    int pfd[2], i, pid; 
    char str[] = "Hello World!\n"; 

    if (pipe(pfd) == -1) 
     syserr("pipe"); 

    printf("pfd[0] = %d, pfd[1] = %d\n", pfd[0], pfd[1]); 
    pid=fork(); 

    switch(pid) { 
     case -1: 
       syserr("fork"); 
     case 0: 
      { 
       printf("I'm child'"); 
       child(pfd); 
      } 
     default:{ /* parent only */ 
      if(pid!=0) 
      { 
       printf("I'm parent'"); 
       dup2(pfd[0],0); //input 
       execl("/bin/wc", "wc", 0);   
      }/*default*/ 
     } /*switch*/ 
    } 
} 
+1

考慮使用'popen'。而且你不需要分配一個「日期」。閱讀[時間(7)](http://man7.org/linux/man-pages/man7/time.7.html)並使用[time(2)](http://man7.org/linux/man -pages/man2/time.2.html),[localtime_r(3)](http://man7.org/linux/man-pages/man3/localtime_r.3.html),[strftime(3)](http ://man7.org/linux/man-pages/man3/strftime.3.html)(這是BTW'date'使用的) –

+2

用'perror'替換'syserr' –

回答

2

記住<stdio.h>被緩衝,並標準輸出通常是行緩衝,至少當它是一個終端。請參閱setvbuf(3)

因此,您應該在適當的地方結束\n的每個printf格式控制字符串或致電fflush(3)。特別是在您的forkexecl之前做fflush(NULL);

也可以在失敗時使用perror(即將syserr的每個呼叫替換爲perror)以瞭解系統調用失敗的原因。見perror(3) & errno(3) & strerror(3)

順便說一句,您的main被錯誤地聲明。編譯時應該啓用所有警告和調試信息(例如,使用gcc -Wall -Wextra -g進行編譯)。改進您的代碼以獲取更多警告。然後使用調試器gdb ...

注意避免zombie processes,你的父進程應該使用一些等待的系統調用像waitpid(2)或等待(2)或wait4(2

+0

謝謝。正如你所說,我編輯了代碼。現在,它看起來像'execl(「/ bin/wc」,「wc」,0);'不起作用。但是wc確實存在於'/ bin/wc'路徑中。 –

+0

現在工作。我必須在child中添加'close(pfd [0]);',並在父項中添加'close(pfd [1]);'。 –

1

現在的作品。我不得不在孩子中添加close(pfd[0]);,在父母中添加close(pfd[1]);

#include <stdio.h> 
#include <pthread.h> 
#include <unistd.h> 
#include <assert.h> 
#include <time.h> 
#include <stdlib.h> 
#include <semaphore.h> 
#include <string.h> 
#include <stdlib.h> 
#include <fcntl.h> 

/* pipe1.c - send information through pipe. */ 


void child(int pfd[]){ 
    printf("I'm in child func\n"); 
    close(pfd[0]); 
    dup2(pfd[1],1); 
    execl("/bin/date", "date", 0); 
} 

int main(){ 
    int pfd[2], pid; 

if (pipe(pfd) == -1) perror("pipe"); 
printf("pfd[0] = %d, pfd[1] = %d\n", pfd[0], pfd[1]); 
fflush(NULL); 
pid=fork(); 
    switch(pid) { 
     case -1: 
       perror("fork"); 
     case 0: 
      { 
        printf("I'm child\n"); 
       child(pfd); 
      } 
     default:{ /* parent only */ 
      if(pid!=0){ 
       printf("I'm daddy\n"); 
       close(pfd[1]); 
       dup2(pfd[0],0); //input 
       execl("/bin/wc", "wc", 0);   
     }/*default*/ 
    } /*switch*/ 
} 
return 0; 
} 
相關問題