Linux inter-process communication: pipe and FIFO

Source: Internet
Author: User

 

Pipe

Http://ldl.wisplus.net/2010/10/01/linux%E8%BF%9B%E7%A8%8B%E9%97%B4%E9%80%9A%E4%BF%A1%EF%BC%9A%E7% AE %A1%E9%81%93/

 

Overview:

Int pipe (INT pipefd [2]);
Call the pipe function inKernelOpening up a pieceBuffer Zone(Called pipeline) is usedUnidirectional CommunicationIt has a read end and a write end, which is passed to the user through the filedes parameter.ProgramTwo file descriptors: filedes [0] points to the read end of pipe, and filedes [1] points to the write end of pipe. Therefore, the user program looks like an open file through read (filedes [0]);
Or write (filedes [1]);Reading and writing data to this file is actually reading and writing the kernel buffer..

Follow these steps to create a pipe:

• The parent process calls pipe to open up pipe and obtains two file descriptors pointing to both ends of the pipeline.
• When the parent process calls fork to create a child process, the child process also has two file descriptors pointing to the same pipeline.
• The parent process closes the read end of the pipeline, and the child process closes the write end of the pipeline. The parent process can write data to pipe, and the child process can read data from pipe. pipe is implemented using a circular queue, and data flows from the write end to the read end, in this way, inter-process communication is realized.

12345678910111213141516171819202122232425262728293031323334 # Include <stdio. h> # Include <stdlib. h> # Include <unistd. h> # Include <sys/Wait. H> # Include <string. h>   Int Main () { Char Buf [20]; Pid_t PID; Int FD [2]; Int N;   Pipe (FD ); // Create an MPS queue If (Pid = fork () <0) // Fork sub-process { Perror ( "Fork error" ); Exit (-1 ); } Else If (Pid = 0) // Sub-process { Close (FD [1]); // Close the write end N = read (FD [0], Buf, 20 ); Write (stdout_fileno, Buf, N ); Close (FD [0]); // Close the read end Exit (0 ); } Else // Parent process { Close (FD [0]); // Close the read end Write (FD [1], "Hello World" , Strlen ( "Hello World" )); Close (FD [1]); // Close the write end Waitpid (PID, null, 0 ); Exit (0 ); } }
Popen and pclose Functions

The standard Io function library provides the popen function, which creates a pipeline andStart another processThis process is read from this pipeStandard InputOr setStandard outputWrite the pipe.
File * popen (const char * command, const char * type );
Int pclose (File * stream );
Popen function: first execute fork, then call exec (SH) to execute command, and return a standard I/O file pointer. (Null is returned for an error)
If the type is "r", the file pointer is connected to the standard output of the command (the process is a read segment and the Command refers to the process as the write end). The parameter "W" is the same.
This command is passed to/bin/sh using the-C flag;
Pclose function: Close the standard I/O Stream created by popen, wait until the command execution ends, and thenReturns the shell termination status.(Error return-1)

12345678910111213141516171819202122232425262728293031 # Include <stdio. h> # Include <stdlib. h> # Include <unistd. h>   # Define pager "$ {Pager:-more}" // If the shell variable pager has been defined and is not empty, use its value; otherwise, use the string more Int Main () { Char Line [100]; File * Fpin, * fpout; If (Fpin = Fopen ( "A.txt" , "R" ) = NULL) { Perror ( "Can't open a.txt" ); Exit (-1 ); } If (Fpout = popen (PAGER, "W" ) = NULL) { Perror ( "Popen error" ); Exit (-1 ); } While ( Fgets (Line, 100, fpin )! = NULL) { If ( Fputs (Line, fpout) = EOF) { Perror ( "Fputs error to pipe" ); Exit (-1 ); } } If (Pclose (fpout) =-1) Perror ( "Pclose error" ); Exit (0 ); }
FIFO

FIFO is named pipe, in the file systemThere is a path name associated with it. Pipe can only be used by unrelated processes, and their common ancestor processes create pipelines. However, through FIFO, unrelated processes can also exchange data

Create FIFO

Int mkfifo (const char * pathname, mode_t mode );
Mode is the access permission (which must be combined with the umask of the process). General file I/O functions can be used in FIFO
Mkfifo function alreadyImplicitly specifiedO_creat | o_excl, that is, either creating a new FIFO or returning an eexist error (the file already exists)

Delete FIFO

Int unlink (const char * pathname );
Unlike pipe, FIFO can be deleted from the file system only through Unlink.

Enable FIFO

Int open (const char * pathname, int flags );
Open the FIFO using the open function. By defaultNot SpecifiedO_nonblock flag

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 // Export o_write.c # Include <stdio. h> # Include <stdlib. h> # Include <unistd. h> # Include <string. h> # Include <errno. h> # Include <fcntl. h> # Define export o_file "/tmp/myfifo"   Int Main () { Int FD = 0; Int N; Char Buf [2, 100];   If (FD = open (export o_file, o_wronly | o_nonblock) <0) // Open in non-blocking mode { Perror ( "Open error" ); Exit (-1 ); } While (1) { Fgets (BUF, 100, stdin ); N = Strlen (BUF ); If (N = write (FD, Buf, n) <0) { If ( Errno = Eagain) Printf ( "The FIFO has not been read yet. Please try later \ n" ); } } Return 0; }   // Export o_read.c # Include <stdio. h> # Include <stdlib. h> # Include <unistd. h> # Include <sys/types. h> # Include <sys/STAT. h> # Include <fcntl. h> # Include <errno. h>   # Define export o_file "/tmp/myfifo"   Int Main () { Char Buf [2, 100]; Int N = 0; Int FD; If (Mkfifo (fifo_file, s_irwxu) <0 )&&( Errno ! = Eexist )) // If the FIFO file does not exist, create it { Perror ( "Mkfifo error" ); Exit (-1 ); } If (FD = open (export o_file, o_rdonly | o_nonblock) <0) // Open in non-blocking mode { Perror ( "Open error" ); Exit (-1 ); } While (1) { If (N = read (FD, Buf, 100) <0) { If ( Errno = Eagain) { Printf ( "No data yet \ n" ); } } Else Write (stdout_fileno, Buf, N ); Sleep (1 ); // Sleep } Unlink (export o_file ); Return 0; }
Read/write of FIFO and pipe:

(1) pipe or FIFO write always adds data to the end of , for their read operations, always returns data from the beginning . If you call lseek for pipe or FIFO, The espipe error is returned.
(2) A file descriptor can be set to non-blocking in the way of 2: (blocking by default)
• you can specify the o_nonblock flag when calling open.
• If the file descriptor has been opened, you can call fcntl to set the o_nonblock flag (pipe can only use this method)
(3) read/write rules:
blocking (default ):
Read-only open
• Read-Only enable in FIFO mode: Return success
• Write-only enable in FIFO mode: the read-only write
• the read-only write is returned: read from empty pipe or empty FIFO
• FIFO or pipe has been read only: data in the pipe or FIFO is blocked or is not opened for writing.
• FIFO or pipe is not opened for writing only: 0 is returned (File Terminator)
write
• FIFO or pipe has been read-only:
the write data volume is not greater than pipe_buf (Atomicity guaranteed): If there is enough space to store, all data is written at a time, if not, go to sleep until the buffer zone contains the number of all bytes to be written.
the write data volume is greater than pipe_buf (Atomicity is not guaranteed ): when the buffer zone is idle, the process tries to write data. After writing all the data, the function returns
• FIFO or pipe is not read-only: generate sigpipe for the thread (terminate the process by default)

O_nonblock settings:
Read-only open
• FIFO has been written and opened only: Return success
• FIFO is not written to open only: Return success
Write only open
• Read-only access to FIFO: a successful result is returned.
• FIFO is not read-only: An enxio error is returned.
Read from an empty pipe or an empty FIFO
• If FIFO or pipe is enabled only, the eagain error is returned.
• FIFO or pipe is not written for open only: 0 is returned (File Terminator)
Write
• FIFO or pipe is read-only:
Write data volume not greater than pipe_buf (Atomicity guaranteed): If there is enough space to store, all data is written at a time. If not, the eagain error is returned (not partially written)
The write data volume is larger than pipe_buf (Atomicity is not guaranteed): If there is enough space to store, all data is written. If not, some data is written and the function returns immediately.
• FIFO or pipe is not read-only: Generate sigpipe for the thread (process terminated by default)

Several additional rules for pipe or FIFO:
• If the amount of data requested to be read exceeds the amount of currently available data, the available data will be returned.
• If the number of data bytes written by the request is smaller than or equal to pipe_buf, the write operation must be atomic (The setting of the o_nonblock flag does not affect atomicity.)
• Data still on the pipe or FIFO when the last one of pipe or FIFO is disabledWill be discarded

Limitations of FIFO and pipe:

• They are half-duplex (unidirectional), that is, data flows only in one direction. Process a flows to process B or process B to process.
• The read and write ends of pipe are passed through the opened file descriptor. Therefore, the two processes to communicate must inherit the pipe file descriptor from their common ancestor. FIFO allows communication between unrelated processes.
• Maximum number of file descriptors opened by a process at any time open_max (obtained by calling sysconf (_ SC _open_max)
• Maximum data size that can be written atomically to pipe or FIFO pipe_buf (usually defined in limits. h)

Summary:

• pipe is generally used in shell, but it can also be used in programs. It is often used to return information from a subroutine to the parent program. Some codes (pipe, fork, close, exec, and waitpid) involved in pipe can be avoided by using popen and pclose, they process the specific details and activate a shell
• FIFO is similar to the pipeline, but they are created using mkfifo and then need to be opened using open. Be careful when opening the pipeline, because there are many rules that restrict the blocking of open (or even deadlock)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.