0

fifo を使用して、file1 の内容を他の file2 にコピーしようとしています。fifo に書き戻したい最初の 4 文字 (file1 から fifo にコンテンツを書き込むときではなく、読み取り中) にそれを file2 にもコピーします。ただし、最初の 4 文字は後ろに追加されず、途中でランダムに挿入されます。私のコードは

int main( int argc, char* argv[] ) {

    int fdes,fdes1;
    pid_t pid;
    ssize_t numRead;

    char readBuff[1];
    char writeBuff[1];
    int readCounter;
    int c=0;

    umask(0);

    if (mkfifo("ajjp.e",0666) == -1  /*make the fifo*/
        && errno != EEXIST)
    {}

    if( argc < 3 ) {
        printf( "Atleast need 2 params " );
        exit(1);
    }

    int to_copy = open( argv[1], 0 );/* file from which contents are to be copied */
    int oo = creat(argv[2], 0666);/* file created where we've to write contents*/

    if ( to_copy == -1  ) {
        printf( "Opening file failed " );
        exit(1);
    }
    if ( (pid = fork()) < 0) /* child process is made*/
        perror("fork error");

    /* in parent process,I'm cwriting contents of file1 to fifo character by character */
    else if(pid>0)
    {
        fdes = open("ajjp.e", O_WRONLY);
        while( (readCounter = read( to_copy, readBuff, sizeof( readBuff ) ) > 0 ) )  {

            write( fdes, readBuff, sizeof( readBuff ) );
        }
        close(to_copy);

    }
/* now, in child process, I opened its read end then I'm reading contents from fifo and writing it to file2(i.e copy_to here) but for first four characters( c< 5 here), I'm writing them to fifo also by opening its write end. */
    else
    {
        fdes1 = open("ajjp.e", O_RDONLY);

        fdes = open("ajjp.e", O_WRONLY);

        if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
            printf("signal");

        int copy_to = open( argv[2], 0666);/* opened the file where we've to write*/
        if ( copy_to == -1  ) {
            printf( "Opening file failed " );
            exit(1);
        }


        for(;;) {

            c++;
            numRead = read(fdes1, readBuff, sizeof(readBuff));/* reading from read end of fifo*/

            if (numRead == 0)
                break;

            /* write to the file2*/
            if (write(copy_to, readBuff, numRead) != numRead)
            {}
            /* for first 4 characters, I am rewriting to the back of fifo*/
            if(c<5)
            {
                write(fdes,readBuff,sizeof(readBuff));
            }
            /*after writing those 4 characters, write end I've closed*/
            if(c==5)
                close(fdes);
        }
        close(fdes);
        close(fdes1);

    }//end else

    return 0;    
}

さて、ターミナルの場合、私は実行します

$ ./a.out a.txt b.txt

a.txt から b.txt にコピーしたいのですが、b.txt には a.txt と最初の 4 文字が含まれており、文字間にランダムに挿入されています。

4

1 に答える 1