简体   繁体   中英

Why parent process reads first from pipe in LINUX

i have run this code and found out that the parent process reads first then child process writes. i want to know why this is happening?
Additionally i also want to know how can i use two pipes in this program.i just want the concept, any code will be appreciated.Thanks

    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>

    main()
    {
            int     fd[2];
            pid_t   childpid;

            pipe(fd);

            if((childpid = fork()) == -1)
            {
                    perror("fork");

            }

            if(childpid == 0)
            {
                    /* Child process closes up input side of pipe */
                    close(fd[0]);
        printf("\nChild writes\n\n");
            }
            else
            {
                    /* Parent process closes up output side of pipe */
                    close(fd[1]);
        printf("parent reads\n\n");
            }
            return 0;
    }

For you queries :-

The parent process reads first then child process writes. i want to know why this is happening ?

After fork() both process work independently, so which process will be scheduled first, it's depend on scheduler.

How can i use two pipes in this program?

open two pipe, one for parents and one for child process. because pipe are unidirectional.

int fd[2];
int fd1[2];

parents will write on fd[1]  child will read from fd[0]
child will write on fd1[1] parents will read from fd1[0]

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