Process Communication--Anonymous pipeline

Source: Internet
Author: User

Sometimes during the process of developing a program, there is data interaction between the two processes. The signaling mechanism enables process communication. It works through an "interrupt-response" asynchronous Pattern. But as far as communication is concerned, the signal is still not enough. Because it is not able to carry any other information. Using only the signaling mechanism to achieve process communication is stretched, and the advantages of the signal are not. Therefore, new methods of interprocess communication must be developed. The "anonymous pipeline" that this article learns is one of the simplest methods.

Basic concepts

Before you talk about the basic concepts of piping, ask a question first. What would you do if you were to design the way the process communicates? The simplest way to do this is to have two processes open the same file, so that you can interact with the information through continuous read and write operations. The concept and principle of piping are similar but not identical to the above methods. Here's a look at the functions for creating pipelinespipe

#include <unistd.h>int pipe(int fd[2]);                    返回值:若成功,返回0,若出错,返回-1

The function returns two file descriptors with a fd[0] fd[1] . Provision: fd[0] for read operations, fd[1] for write operations. After the pipeline is created, the usual practice is to call the fork function, then the child process inherits the parent fd[0] process fd[1] . So the parent process and the child process establish a "pipeline" of communication through these two file descriptors. In communication, the parent process and the child process either shut down the read end or a write-down to achieve half-duplex data transfer. That is, traffic can only go in one direction and not at the same time. The following diagram helps to understand how the pipeline works:

This is referred to as "anonymity" because it can only be applied in two processes that are related to each other. Not all two processes can communicate in this way.

A simple example

The following example uses a pipeline to implement a child process that passes a piece of information to the parent process, a simple function that the parent process receives and prints out.

intMainvoid){    intN; intfd[2];    pid_t pid; Charline[1024x768]; if(Pipe (FD) <0)        return; if(PID = fork ()) <0)         return; Else if(PID >0) {Close (fd[0]); Write (fd[1],"Hello world\n", A); }    Else{Close (fd[1]); N= Read (fd[0], line,1024x768); printf ("The recv msg is%s\n", line); }    return(0);}

Watch out.

Here is a note about the point of attention in the operation of the pipe to the reading end and the writing end.

    • If the write end is not closed, perform the read operation:

      1. If there is no data in the pipeline, read it will block.
      2. The buffer of the pipeline is also of a size, and this value is recorded in PIPE_BUF . The number of bytes passed in by the Read function, the actual number of bytes in the pipeline, and the size of the pipe buffer will have a size order relationship between them. The return value of read is also related to the relationship between the three. Just remember, however, that the read number of bytes actually read is returned, and the return value check is done to avoid errors in programming.
    • In the case of write-off, do the read following:

      There read is no error at this time, but the return value is 0.

    • If the read end is not closed, do the write following:

      If the buffer for the pipe is full, the write operation is blocked

    • In the case of read-side shutdown, do the write following:

      This situation is dangerous, write return 1, error set to EPIPE , and generate a SIGPIPE signal.

Popen pclose function

As mentioned in the Process control, if you want to invoke the shell command or script file inside the program, you can fork implement it by itself, or call the system function directly. Now we have one more method, which is the popen function, and the popen function passes the pipeline mechanism to pass the output of the execution shell command to the parent process, or the parent process can pass parameters to the shell command through the pipeline. This implementation also greatly facilitates the needs of our programming. The following is popen pclose a statement of the function, and a few more examples to deepen the impression.

#include <stdio.h>FILE *popen(const char *cmdstring, const char *type);                            返回值:若成功,返回文件指针;若出错,返回NULLint pclose(FILE *fp);                            返回值:若成功,返回cmdstring的终止状态;若出错,返回-1

When popen the function passes in the type "r" , it indicates that the program can read the result of the execution from the file pointer it returns cmstring , and it actually joins the child process stdout with the returned file pointer. As shown in the following:

When popen the type of the function is passed in "w" , it means that the parent process can pass parameters to the child process through a file pointer, and its understanding can be aided by:

Two simple examples of the use of a popen function:

/*Test Popen Output*/intMain () {FILE*FP;    pid_t pid; Char*cmd ="Ls-al"; Charline[1024x768]; if(fp = popen (cmd,"R")) ==NULL)return; //Get and print the data from child processFread (Line,sizeof(Char),1024x768, FP); printf ("%s\n", line);    Pclose (FP); return;}/*Test Popen Input*/intMain () {FILE*FP;    pid_t pid; Char*cmd ="Cat"; Char*msg ="Hello world\n"; if(fp = popen (cmd,"W")) ==NULL)return; //get the params form the parent processFwrite (MSG,sizeof(Char), A, FP);    Pclose (FP); return;}

Process Communication--Anonymous pipeline

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: 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.