linux進程通訊:管道(pipe)

man 7 pipe

PIPE(7)                    Linux Programmer’s Manual                   PIPE(7)

NAME
       pipe - overview of pipes and FIFOs

DESCRIPTION
       Pipes  and  FIFOs (also known as named pipes) provide a unidirectional interprocess communication channel.  A pipe has a read end and a write end.  Data written to
       the write end of a pipe can be read from the read end of the pipe.

       A pipe is created using pipe(2), which creates a new pipe and returns two file descriptors, one referring to the read end of the pipe, the other referring  to  the
       write end.  Pipes can be used to create a communication channel between related processes; see pipe(2) for an example.

       A  FIFO  (short  for  First  In  First Out) has a name within the file system (created using mkfifo(3)), and is opened using open(2).  Any process may open a FIFO,
       assuming the file permissions allow it.  The read end is opened using the O_RDONLY flag; the write end is opened using the O_WRONLY flag.  See fifo(7) for  further
       details.  Note: although FIFOs have a pathname in the file system, I/O on FIFOs does not involve operations on the underlying device (if there is one).

   I/O on Pipes and FIFOs
       The  only  difference  between pipes and FIFOs is the manner in which they are created and opened.  Once these tasks have been accomplished, I/O on pipes and FIFOs
       has exactly the same semantics.

       If a process attempts to read from an empty pipe, then read(2) will block until data is available.  If a process attempts to write to a full pipe (see below), then
       write(2) blocks until sufficient data has been read from the pipe to allow the write to complete.  Non-blocking I/O is possible by using the fcntl(2) F_SETFL oper-
       ation to enable the O_NONBLOCK open file status flag.

       The communication channel provided by a pipe is a byte stream: there is no concept of message boundaries.

       If all file descriptors referring to the write end of a pipe have been closed, then an attempt to read(2) from the pipe will see end-of-file (read(2)  will  return
       0).  If all file descriptors referring to the read end of a pipe have been closed, then a write(2) will cause a SIGPIPE signal to be generated for the calling pro-
       cess.  If the calling process is ignoring this signal, then write(2) fails with the error EPIPE.  An application that uses pipe(2) and fork(2) should use  suitable
       close(2) calls to close unnecessary duplicate file descriptors; this ensures that end-of-file and SIGPIPE/EPIPE are delivered when appropriate.

       It is not possible to apply lseek(2) to a pipe.
   Pipe Capacity
       A  pipe  has  a limited capacity.  If the pipe is full, then a write(2) will block or fail, depending on whether the O_NONBLOCK flag is set (see below).  Different
       implementations have different limits for the pipe capacity.  Applications should not rely on a particular capacity: an application should be designed  so  that  a
       reading process consumes data as soon as it is available, so that a writing process does not remain blocked.

       In  Linux versions before 2.6.11, the capacity of a pipe was the same as the system page size (e.g., 4096 bytes on i386).  Since Linux 2.6.11, the pipe capacity is
       65536 bytes.

   PIPE_BUF
       POSIX.1-2001 says that write(2)s of less than PIPE_BUF bytes must be atomic: the output data is written to the pipe as a contiguous sequence.  Writes of more  than
       PIPE_BUF  bytes  may  be  non-atomic:  the  kernel may interleave the data with data written by other processes.  POSIX.1-2001 requires PIPE_BUF to be at least 512
       bytes.  (On Linux, PIPE_BUF is 4096 bytes.)  The precise semantics depend on whether the file descriptor is non-blocking (O_NONBLOCK), whether there  are  multiple
       writers to the pipe, and on n, the number of bytes to be written:

       O_NONBLOCK disabled, n <= PIPE_BUF
              All n bytes are written atomically; write(2) may block if there is not room for n bytes to be written immediately

       O_NONBLOCK enabled, n <= PIPE_BUF
              If  there is room to write n bytes to the pipe, then write(2) succeeds immediately, writing all n bytes; otherwise write(2) fails, with errno set to EAGAIN.

       O_NONBLOCK disabled, n > PIPE_BUF
              The write is non-atomic: the data given to write(2) may be interleaved with write(2)s by other process; the write(2) blocks until n bytes have been written.

       O_NONBLOCK enabled, n > PIPE_BUF
              If  the  pipe  is  full, then write(2) fails, with errno set to EAGAIN.  Otherwise, from 1 to n bytes may be written (i.e., a "partial write" may occur; the
              caller should check the return value from write(2) to see how many bytes were actually written), and these bytes may be interleaved  with  writes  by  other
              processes.

   Open File Status Flags
       The only open file status flags that can be meaningfully applied to a pipe or FIFO are O_NONBLOCK and O_ASYNC.

       Setting  the  O_ASYNC flag for the read end of a pipe causes a signal (SIGIO by default) to be generated when new input becomes available on the pipe (see fcntl(2)
       for details).  On Linux, O_ASYNC is supported for pipes and FIFOs only since kernel 2.6.

   Portability notes
       On some systems (but not Linux), pipes are bidirectional: data can be transmitted in both directions between the pipe ends.  According to POSIX.1-2001, pipes  only
       need to be unidirectional.  Portable applications should avoid reliance on bidirectional pipe semantics.

 

管道讀寫規則

當沒有數據可讀時linux

  • O_NONBLOCK disable:read調用阻塞,即進程暫停執行,一直等到有數據來到爲止。
  • O_NONBLOCK enable:read調用返回-1,errno值爲EAGAIN。

當管道滿的時候app

  • O_NONBLOCK disable: write調用阻塞,直到有進程讀走數據
  • O_NONBLOCK enable:調用返回-1,errno值爲EAGAIN

若是全部管道寫端對應的文件描述符被關閉,則read返回0less

若是全部管道讀端對應的文件描述符被關閉,則write操做會產生信號SIGPIPEide

當要寫入的數據量不大於PIPE_BUF時,linux將保證寫入的原子性。ui

當要寫入的數據量大於PIPE_BUF時,linux將再也不保證寫入的原子性。this

 

二,驗證示例

示例一:O_NONBLOCK disable:read調用阻塞,即進程暫停執行,一直等到有數據來到爲止。

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

int main(void)
{
    int fds[2];
    if(pipe(fds) == -1){
        perror("pipe error");
        exit(EXIT_FAILURE);
    }   
    printf("begin test pipe\n");
    pid_t pid;
    pid = fork();
    if(pid == -1){
        perror("fork error");
        exit(EXIT_FAILURE);
    }   
    if(pid == 0){ 
        close(fds[0]);//子進程關閉讀端
        sleep(10);
        write(fds[1],"hello",5);
        exit(EXIT_SUCCESS);
    }   

    close(fds[1]);//父進程關閉寫端
    char buf[10] = {0};
    read(fds[0],buf,10);
    printf("receive datas = %s\n",buf);
    return 0;
}

運行結果:atom

說明:管道建立時默認打開了文件描述符,且默認是阻塞(block)模式打開spa

因此這裏,咱們讓子進程先睡眠10s,父進程由於沒有數據從管道中讀出,被阻塞了,直到子進程睡眠結束,向管道中寫入數據後,父進程纔讀到數據code

示例二:O_NONBLOCK enable:read調用返回-1,errno值爲EAGAIN。

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

int main(void)
{
    int fds[2];
    if(pipe(fds) == -1){
        perror("pipe error");
        exit(EXIT_FAILURE);
    }   
    printf("begin test pipe\n");
    pid_t pid;
    pid = fork();
    if(pid == -1){
        perror("fork error");
        exit(EXIT_FAILURE);
    }   
    if(pid == 0){ 
        close(fds[0]);//子進程關閉讀端
        sleep(10);
        write(fds[1],"hello",5);
        exit(EXIT_SUCCESS);
    }   

    close(fds[1]);//父進程關閉寫端
    char buf[10] = {0};
    int flags = fcntl(fds[0], F_GETFL);//先獲取原先的flags
    fcntl(fds[0],F_SETFL,flags | O_NONBLOCK);//設置fd爲非阻塞模式
    int ret;
    ret = read(fds[0],buf,10);
    if(ret == -1){

        perror("read error");
        exit(EXIT_FAILURE);
    }   

    printf("receive datas = %s\n",buf);
    return 0;
}

運行結果:進程

示例三:若是全部管道寫端對應的文件描述符被關閉,則read返回0

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

int main(void)
{
    int fds[2];
    if(pipe(fds) == -1){
        perror("pipe error");
        exit(EXIT_FAILURE);
    }   
    printf("begin test pipe\n");
    pid_t pid;
    pid = fork();
    if(pid == -1){
        perror("fork error");
        exit(EXIT_FAILURE);
    }   
    if(pid == 0){ 
        close(fds[1]);//子進程關閉寫端
        exit(EXIT_SUCCESS);
    }   

    close(fds[1]);//父進程關閉寫端
    char buf[10] = {0};

    int ret;
    ret = read(fds[0],buf,10);
    printf("ret = %d\n", ret);

    return 0;
}

運行結果:

可知確實返回0,表示讀到了文件末尾,並不表示出錯

示例四:若是全部管道讀端對應的文件描述符被關閉,則write操做會產生信號SIGPIPE

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <signal.h>

void sighandler(int signo);
int main(void)
{
    int fds[2];
    if(signal(SIGPIPE,sighandler) == SIG_ERR)
    {
        perror("signal error");
        exit(EXIT_FAILURE);
    }
    printf("begin test pipe\n");
    if(pipe(fds) == -1){
        perror("pipe error");
        exit(EXIT_FAILURE);
    }
    pid_t pid;
    pid = fork();
    if(pid == -1){
        perror("fork error");
        exit(EXIT_FAILURE);
    }
    if(pid == 0){
        close(fds[0]);//子進程關閉讀端
        exit(EXIT_SUCCESS);
    }

    close(fds[0]);//父進程關閉讀端
    sleep(1);//確保子進程也將讀端關閉
    int ret;
    ret = write(fds[1],"hello",5);
    if(ret == -1){
        printf("write error\n");
    }
    return 0;
}

void sighandler(int signo)
{
    printf("catch a SIGPIPE signal and signum = %d\n",signo);
}

運行結果:

可知當全部讀端都關閉時,write時確實產生SIGPIPE信號

相關文章
相關標籤/搜索