简体   繁体   中英

How can I write twice on the same pipe?

I want parent to read from standard input and write it on pipe then the child read from this pipe and convert it to upper case and send it back on another pipe to the parent then the parent print it on standard output then write more one time.

The parent doesn't write anthor time

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#define bufsize 200

int main(int argc,char*argv[])
{
    char buf[bufsize];
    char buf2[bufsize];
    int x;
    int child;
    int fd[2];
    int fd1[2];
    int nbytes,mbytes;
    int i,j,k;
    int status=0;

    if(pipe(fd)==-1)
        printf("pipe");
    if(pipe(fd1)==-1)
        printf("pipe");

    switch(fork())
    {
        case -1 : printf("fork");
        case 0:{
            //for(k=1;k<3;k++)
            //{close(fd[1]);
            nbytes = read(fd[0], buf, bufsize);   

            for(i=0;i<=strlen(buf);i++){
                if(buf[i]>=97&&buf[i]<=122)
                buf[i]=buf[i]-32;
            }//end for

            close(fd1[0]);
            write(fd1[1], buf, nbytes);
            _exit(EXIT_SUCCESS);   

        }//end child

        default:{
            for(j=1;j<3;j++){
                close(fd[0]);
                printf("Enter any thing:\n");
                x=read(STDIN_FILENO, buf, bufsize);
                write(fd[1],buf,x);

                close(fd1[1]);
                mbytes = read(fd1[0], buf, bufsize);   
                close(fd1[0]); 
                write(STDOUT_FILENO, buf, mbytes);
            }
            //wait(status);
            exit(EXIT_SUCCESS);
        }//end default
    }//end switch
}

If you want to write twice to the same pipe, don't close it after you write to it the first time. Only close it when you are done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM