我应该如何等待来自FIFO进程的子进程的输入

时间:2014-02-19 05:03:14

标签: c fork pipe fifo

我在使用fifos时遇到了麻烦,我希望父母创建2个fifos并等待孩子将其用户输入的日期,时间和系统日期和时间与uid一起写入fifo 1并且一旦收到此父级已经然后打开一个日志文件并将内容写入日志文件和fifo2。并且孩子将读取fifo2并显示结果

#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

1 个答案:

答案 0 :(得分:0)

在您提交的代码中,子进程只打开两个命名管道并且存在。如果您正确缩进代码,您将意识到问题。您还想使用“pipe()”进行此类应用。