简体   繁体   English

Unix:如果进程终止,管道(半双工)会发生什么

[英]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. 我试图证明我的疑问之一,即两个不相关的进程可以共享半双工管道的fd并进行通信。

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) ). 每个进程都有其自己的单独的打开文件描述符集(请注意,每个文件的打开文件描述符与每个系统范围的打开文件描述之间的区别,在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. 如果要在进程间共享一个文件描述符,你需要或者继承它在fork(2)或通过把它传递unix(7)域套接字经由sendmesg(2)SCM_RIGHTScmesg(3)报头。

(On Linux, you can also pass around paths to /proc/[PID]/fd/... , and other systems may have their own non-portable equivalents). (在Linux上,您还可以传递/proc/[PID]/fd/...路径,其他系统可能有其自己的不可移植等效项)。

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. pipe()创建一个管道,一个可用于进程间通信的单向数据通道。 The array pipefd is used to return two file descriptors referring to the ends of the pipe. 数组pipefd用于返回两个引用管道末端的文件描述符。 pipefd[0] refers to the read end of the pipe. pipefd [0]指向管道的读取端。 pipefd[1] refers to the write end of the pipe. pipefd [1]指向管道的写端。 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. 在另一端过程中得到SIGPIPE信号。

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; 上面的程序创建一个管道,然后fork(2)创建一个子进程。 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)). 在fork(2)之后,每个进程都关闭不需要管道的描述符(请参阅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. 然后,父级将程序的命令行参数中包含的字符串写入管道,而子级一次从管道读取该字符串一个字节,并在标准输出中回显该字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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