简体   繁体   中英

Unix : What happens to a pipe(half-duplex) if the process dies

I am trying to prove one of my doubts, that two non-related processes can share the fd of half-duplex pipe and have communication.

I have created two programs for that. But then I had this another question, that what happens to the pipe if process dies?Because my reader got some garbage message, when I printed out the message.

Writer

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main()
{
    int fd[2];
    char str[] = "hello\n";
    if(pipe(fd) < 0)
        perror("Pipe creation failed\n");

    //Since i am a writer, i should close the reading end as a best practice
    close(fd[0]);

    /*
    The processes need not to be related processes, in order to use the half duplex pipes. fd is just a number/identifier
    which can be shared across different processes 
    */
    printf("Hey there !!! use this file descriptor for reading : %d\n", fd[0]);

    //writing message   
    write(fd[1],str,strlen(str)+1);
    return 0;
}

Reader

#include <stdio.h>
#include <unistd.h>

int main()
{
    int fd,bytesRead;
    char buffer[1024];

    printf("please enter the fd :");
    scanf("%d",&fd);

    bytesRead = read(fd,buffer,1024);

    printf("Bytes Read : %d\nMessage : %s\n", bytesRead, buffer);
    return 0;
}

You can't do this.

The table of file descriptors is per-process; every process has its own separate set of open file descriptors (note the distinction between open file descriptors , which are per-process, and open file descriptions , which are system-wide, discussed in open(2) ). If you want to share a file descriptor between processes, you need to either inherit it over a fork(2) or pass it through a unix(7) domain socket via sendmesg(2) with SCM_RIGHTS in the cmesg(3) header.

(On Linux, you can also pass around paths to /proc/[PID]/fd/... , and other systems may have their own non-portable equivalents).

What is happening in your case is that the read is failing (you're giving it a file descriptor which is not open), leaving your buffer with uninitialized garbage. Since you don't check the return value, you never know that it failed.

In pipe man page,

pipe() creates a pipe, a unidirectional data channel that can be used for interprocess communication. The array pipefd is used to return two file descriptors referring to the ends of the pipe. pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe. Data written to the write end of the pipe is buffered by the kernel until it is read from the read end of the pipe.

The pipe is mainly used for the related process(parent and child). You are not able to use the pipe for non related process.

In related process, one end is closed. In other end process gets the SIGPIPE signal.

Example program using pipe :-

   #include <sys/wait.h>
   #include <stdio.h>
   #include <stdlib.h>
   #include <unistd.h>
   #include <string.h>

   int
   main(int argc, char *argv[])
   {
       int pipefd[2];
       pid_t cpid;
       char buf;

       if (argc != 2) {
        fprintf(stderr, "Usage: %s <string>\n", argv[0]);
        exit(EXIT_FAILURE);
       }

       if (pipe(pipefd) == -1) {
           perror("pipe");
           exit(EXIT_FAILURE);
       }

       cpid = fork();
       if (cpid == -1) {
           perror("fork");
           exit(EXIT_FAILURE);
       }

       if (cpid == 0) {    /* Child reads from pipe */
           close(pipefd[1]);          /* Close unused write end */

           while (read(pipefd[0], &buf, 1) > 0)
               write(STDOUT_FILENO, &buf, 1);

           write(STDOUT_FILENO, "\n", 1);
           close(pipefd[0]);
           _exit(EXIT_SUCCESS);

       } else {            /* Parent writes argv[1] to pipe */
           close(pipefd[0]);          /* Close unused read end */
           write(pipefd[1], argv[1], strlen(argv[1]));
           close(pipefd[1]);          /* Reader will see EOF */
           wait(NULL);                /* Wait for child */
           exit(EXIT_SUCCESS);
       }
   }

The above program creates a pipe, and then fork(2)s to create a child process; the child inherits a duplicate set of file descriptors that refer to the same pipe. After the fork(2), each process closes the descriptors that it doesn't need for the pipe (see pipe(7)). The parent then writes the string contained in the program's command-line argument to the pipe, and the child reads this string a byte at a time from the pipe and echoes it on standard output.

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