2014-02-19 38 views
0

我在使用fifos時遇到了麻煩,我希望父母創建2個fifo並等待孩子將其用戶輸入的日期,時間和系統日期和時間寫入uid到fifo 1,一旦收到這個父節點,它必須打開一個日誌文件,並將內容寫入日誌文件和fifo2。和孩子會讀FIFO2並顯示結果我應該如何等待來自子進程的輸入與FIFO

#include<stdio.h> 
#include<fcntl.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include<time.h> 
int main() 
{ 
    int pid; 
    char buff[64]; 
    int ret,ret2; 
    FILE *cfp; 
    char fifoName[]="/tmp/testfifo23"; 
    char fifoName2[]="/tmp/testfifo22"; 
    FILE *cfp2; 
    FILE *pfp2; 
    char array[36],bufftime[36],buffread[64]; 
    FILE *pfp,*pfp2; 


    //Time Calculation 

    time_t rawtime; 

    time (&rawtime); 
    struct tm *timeinfo = localtime (&rawtime); 
    strftime(array, sizeof(array)-1, "%d.%m.%y %H:%M:%S", timeinfo); 

    // 

    if((pid=fork())>=0) 
    { 
     if(pid==0) //child Process 
     { 

      ret2 = mknod(fifoName, S_IFIFO | 0600, 0); 

      if(ret < 0) 
      { 
       printf("Unable to create fifos"); 
       exit(0); 
      } 
      ret2 = mknod(fifoName2, S_IFIFO | 0600, 0); 

      if(ret2 < 0) 
      { 
       printf("Unable to create fifos"); 
       exit(0); 
      } 

     } 
     else 
     { 
      sleep(3); 
      printf("Enter The date"); 

      if((fgets(buff,8,stdin)!=NULL)) 
      { 
       printf("Job done %s",buff); 
      } 
      printf("\n Enter The time"); 
      if((fgets(bufftime,8,stdin)!=NULL)) 
      { 

       printf("\nJob done %s",bufftime); 
      } 

      cfp = fopen(fifoName,"w"); 
      if(cfp == NULL) 
      { 
       printf("Unable to open fifo for writing"); 
       exit(0); 
      } 
      ret=fprintf(cfp,"%s %s %s %u",buff,bufftime,array,getuid()); 
      // fflush(cfp); 
      unlink(fifoName); 
      //close(fifoName); 
      cfp2= fopen(fifoName2,"r"); 

      if(cfp2 == NULL) 
      { 
       printf("Unable to open fifo for reading"); 
       exit(0); 
      } 
      ret=fscanf(cfp2,"%s",&buffread); 
      if(ret < 0) 
       printf("Error reading from named pipe"); 
      fclose(cfp2); 
      printf("%s",buffread); 
      unlink(fifoName); /* Delete the created fifo */ 
      unlink(fifoName2); 
      exit(0); 

     } 
     else 
     { 
      printf("Error Occured"); 

     } 


     return 0; 
    } 
    // Enter code here 

回答

0

在您所提交的代碼,子進程只打開兩個命名管道和存在。如果你正確縮進你的代碼,你會意識到這個問題。你也想使用「管道()」這種應用程序。