Linux interprocess communication Learning: How to use Named Pipes

Source: Internet
Author: User
Tags anonymous file system printf linux

In the previous article--linux interprocess communication--Using anonymous pipes, we saw how to use anonymous pipes to pass data between processes, as well as seeing a flaw in this approach, which is that these processes are initiated by a common ancestor process, This brings inconvenience to us in exchanging data between unrelated processes. Another way of communicating the process, named Pipes, is described here to address the problem of communication between unrelated processes.

First, what is named pipe

A named pipe, also known as a FIFO file, is a special type of file that exists as a filename in the file system, but behaves like a pipe (anonymous pipe) that was previously spoken without a name.

Because everything in Linux can be considered a file, the use of named pipes becomes very consistent with file operations, and makes it easy to use, and we can use them as usual file names in commands.

Second, create a named pipe

We can use one of two functions to create a named pipe, and their prototypes are as follows:

#include <sys/types.h>  
#include <sys/stat.h>  
int mkfifo (const char *filename, mode_t mode);  
int Mknod (const char *filename, mode_t mode | S_ififo, (dev_t) 0);

Both of these functions create a FIFO file, note that you create a file that really exists in the file system, filename specifies the filename, and mode specifies the file's read and write permissions.

Mknod is an older function, and using the MKFIFO function is simpler and more canonical, so it is advisable to use Mkfifo rather than mknod where possible.

Third, access to Named pipes

1. Open FIFO file

As with opening other files, the FIFO file can also be opened using the open tune. Note that the MKFIFO function simply creates a FIFO file, whether to use named pipes or to open it.

But there are two points to be aware of, 1, is the program can not open the FIFO file in O_rdwr mode to read and write operations, and its behavior is not clearly defined, because such as a pipeline to read/write open, the process will be read back to their own output, and we usually use FIFO only for one-way data transmission. 2, is passed to open call is the FIFO pathname, rather than the normal file.

There are usually four ways to open a FIFO file,

Open (const char *path, o_rdonly);//1  
Open (const char *path, O_RDONLY | O_nonblock);//2  
Open (const char *path, o_wronly);//3  
Open (const char *path, O_WRONLY | O_nonblock);//4

In the second argument of the call to the open function, you see an unfamiliar option O_nonblock, the option O_nonblock represents non-blocking, plus this option, which means that the open call is non-blocking, and if this option is not, the open call is blocked.

What happens to the blocking of an open call? Quite simply, for a FIFO file that is opened in read-only (o_rdonly), if the open call is blocked (that is, the second argument is o_rdonly), it does not return unless a process opens the same FIFO in write mode. If the open call is non-blocking (that is, the second parameter is O_rdonly | O_nonblock), the open call succeeds and returns immediately, even if no other process opens the same FIFO file in write mode.

For FIFO files opened in write-only (o_wronly), if the open call is blocked (that is, the second argument is o_wronly), the open call is blocked until a process opens the same FIFO file as read-only If the open call is non-blocking (that is, the second parameter is O_wronly | O_nonblock), open always returns immediately, but if no other process opens the same FIFO file as read-only, the open call returns-1 and the FIFO is not opened.

Iv. using FIFO to implement communication between processes

Said so much, the following is an example of a program to illustrate how two processes through FIFO to achieve communication bar. There are two source files, a fifowrite.c, which creates pipelines when needed, and then writes data to the pipeline, which is provided by the file Data.txt, size 10M, and the contents are all character ' 0 '. Another source file is FIFOREAD.C, which reads data from the FIFO and saves the read data to another file DataFormFIFO.txt. In order to make the program more concise, ignoring the success of some function calls check.

FIFOWRITE.C's source code is as follows:

#include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <limits.h> #include & lt;sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <string.h> int main (  
    {const char *fifo_name = "/tmp/my_fifo";  
    int pipe_fd =-1;  
    int data_fd =-1;  
    int res = 0;  
    const int open_mode = o_wronly;  
    int bytes_sent = 0;  
      
    Char buffer[pipe_buf + 1];  
        if (Access (fifo_name, F_OK) = = 1) {//pipeline file does not exist//create named pipe res = Mkfifo (fifo_name, 0777);  
            if (res!= 0) {fprintf (stderr, "Could not create FIFO%s\n", fifo_name);  
        Exit (Exit_failure);  
    } printf ("Process%d opening FIFO o_wronly\n", Getpid ());  
    Open the FIFO file in write-only mode, open the data file as read-only pipe_fd = open (Fifo_name, open_mode);  
    DATA_FD = open ("Data.txt", o_rdonly); printf ("Process%d result%d\n", Getpid (), piPE_FD);  
        if (pipe_fd!=-1) {int bytes_read = 0;  
        Reading data to a data file Bytes_read = Read (data_fd, buffer, pipe_buf);  
        Buffer[bytes_read] = ' the ';  
            while (Bytes_read > 0) {//write data to FIFO file res = write (pipe_fd, buffer, bytes_read);  
                if (res = = 1) {fprintf (stderr, "Write error on pipe\n");  
            Exit (Exit_failure);  
            Number of bytes written//accumulated, and continue to read data Bytes_sent = res;  
            Bytes_read = Read (data_fd, buffer, pipe_buf);  
        Buffer[bytes_read] = ' the ';  
        Close (PIPE_FD);  
    Close (DATA_FD);  
      
    else exit (exit_failure);  
    printf ("Process%d finished\n", getpid ());  
Exit (exit_success); }

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/Linux/

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.