2014-02-19 40 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

在您所提交的代码,子进程只打开两个命名管道和存在。如果你正确缩进你的代码,你会意识到这个问题。你也想使用“管道()”这种应用程序。