Linux----interprocess communication-pipeline and two named pipes implement process bidirectional communication __linux

Source: Internet
Author: User
Tags anonymous

In Linux systems, there are times when multiple processes work together to accomplish a task, between processes or between threads that sometimes need to pass information, and sometimes to coordinate with each other, interprocess communication occurs (interprocess communication or IPC)

Signals are also a mechanism for interprocess communication, although its main function is not this, one process sends a signal to another process, and the message is a signal number, and when the Sigqueue () function is used to send a signal, it can also bind data (integer digits or pointers) to the signal and enhance the ability to deliver the message, though It is still not advisable to use signals as a conventional means of interprocess communication.

Inter-process communication means:
1, Communication class: mainly in the process of passing messages (Message Queuing), exchange of data (by sharing a piece of memory to complete the exchange of information)
2, Synchronization classes: coordination between the operation of the process, some operations, multiple processes can not be executed simultaneously, Need to use some synchronization class tools

Anonymous pipeline:

The first widely used inter-process communication tool, in the day-to-day execution of the shall command, the pipeline will be heavily used, the pipe will be shared by a blood-related process, the equivalent of creating a home public place (critical resources), each family member can store information (critical area) in the inside, waiting for another member to take away the information , after reading is burned, (read the contents of the pipeline is expendable, read it will not appear in the pipeline), any time the family public places can only have a member to access the critical resources, the access period to support atomicity (critical resource operation success or failure)

The substance of the pipe:
The kernel maintains a buffer associated with the pipeline file, operates on the pipe file, and is converted by the kernel into the operation of the buffer.

Defects: can only be used between blood-related processes, such as between parent-child processes

#include <unistd.h>
int pipe (pipefd[2]);
pipefd[2]//the array used to return the file descriptor pipefd[0]//read-open,
pipefd[1]//for
write-open, and
invoke fork to create a parent-child process to communicate after the write-end//typically calls pipe () , for the flow of pipeline data, either the parent process (write, close the read end), the subprocess (read, close the write end), or the subprocess (write, close the read end), the parent process (read, close the write end), between this, Both sides can call read (for read process) and write (for writing process) to open file descriptor for read

/write rule
1, read a write-side closed pipe, after all the data read, the read returned 0 to indicate that the file to the end of

2, If you write a read-side closed pipe, then generate a sigpipe signal, catch signal write error returns

3, mutual exclusion and atomicity, at the time of writing, the read end does not allow access to the pipe, and the number of bytes written unread should be less than or equal to PIPE_BUF ( typically 4096 bytes) specified cache size

//When all the read and write ends are closed, the pipe can be destroyed


Pipe in general, one-way communication, otherwise there will be confusion in content, you can establish two of channels to support two-way communication

#include <stdio.h> #include <sys/wait.h> #include <unistd.h> #include <stdlib.h> #include <
    string.h> int main () {int pipefd[2];//after creation returns two file descriptors pipefd[0]--read end pipefd[2]--write end pid_t cpid;

    Char buf;
        if (pipe (PIPEFD) = = 1)//Create pipeline {perror ("pipe");
    Exit (Exit_failure);
        Cpid = fork ()//Create subprocess if (cpid<0) {perror ("fork cpid error");
    Exit (Exit_failure);
        } if (cpid = = 0)//child {close (pipefd[0));//Closes the file descriptor 0, reads the end int i = 0;
        char* _MESG = NULL;  while (i<20) {_mesg = "Hello Father!")
            I am child.\n ";
            Write (pipefd[1], _MESG, strlen (_MESG) +1);
            Sleep (1);
        i++;
        } else//father {Close (pipefd[1]);//The parent process writes ARGV[1] to the pipe, closing the read-side Char _mesg_f[100];
        int j = 0;
            while (J <) {memset (_mesg_f, ' * ', sizeof (_mesg_f)); Read (piPefd[0], _mesg_f, sizeof (_mesg_f));
            Sleep (3);
            printf ("%s\n", _mesg_f);
        j + +;
} return 0;

 }

Pipe Memory Area Size:

1, the essence of the pipeline is a piece of memory area, natural size, pipe default size of 65536 bytes (2 of 16 times), is a buffer in the kernel memory, you can use FCNTL to obtain and modify this is worth the size

pipe_capacity = Fcntl (FD,? F_GETPIPE_SZ)
//Get pipe size

ret  = Fcntl (FD,? f_setpipe_sz,size);
Set the pipe size

pipe memory size must be set between the page size and top values
pipe size, write should be cautious, can not write a large number of data, once the pipeline fills, write will block, for the read end, to read the data in time to prevent the pipeline is full, causing write blocking.

2, Pipe_buf. Defines the size of the kernel pipeline buffer, the size of which is set by the kernel, which can be traced only to a single command, and pipe capacity refers to the maximum value of the pipe, that is, the capacity, which is a buffer in the kernel memory

Named pipe FIFO:

In order to solve the nameless pipeline introduced, and similar to the anonymous pipeline, the biggest difference is that there are entity files associated with, because there are entity files, unrelated unrelated processes can also communicate with each other

#include <sys/types.h>
#include <sys/stst.h>
int mkfifo (const char* pathname,mode_t mode)
Pathname  //file name to create or open
mode  //access Access limit

//Command creation: MKFIFO [m mode] pathname (create named pipe file name)
//        Mknod [m mode] pathname p (p means to create named pipes)
from the outside, I am a FIFO file with a filename, any process can be opened
from the core, the same as the anonymous pipe,

if (Mkfifo ("/ Temp/fifo ", s_ififo|0666) = = 1)//use
{
   perror (" Mkfifo error ") as far as possible;
   Exit (1);
}
if (Mknod ("/temp/fifo", s_ififo|0666) = = 1)
{
   perror ("Mkfifo error");
   Exit (1);
}

S_ififo | 0666    indicates the right to create a named pipe

Implementing a process with two named pipes to achieve two-way communication

The code is as follows:

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.