Pipeline for "UNIX network programming" interprocess communication

Source: Internet
Author: User
Tags fread readable

The pipeline is the earliest form of inter-process communication between UNIX, which exists in all UNIX implementations. For piping, there are a few things to know about this:

1, it is half-duplex, that is, the data can only flow in one direction. While in some UNIX implementations, pipelines can be full-duplex. However, some settings are required for the system. In a Linux system, it is half-duplex.

2, it has no name. So it can only be used between processes that have a common ancestor.

The pass is often used between parent and child processes. This, though, has been corrected with the increase in the "famous pipeline FIFO". But they should be seen as two different ways of communicating between processes.

3, it is created by the pipe function, read and write function access, provide one-way data flow. Except pipe. In the C function library, there is another function Popen complete the creation of a new pipeline, the start of a new process, the shutdown of the pipeline, running a shell command, waiting for a command to terminate a series of operations.


Examples of piping use:

In the shell command, we often use the CMD1 | CMD2 "This type of command, between Cmd1 and CMD2, is connected through a pipeline.

The shell is responsible for the standard input standard output of two commands:

The standard input from the CMD1 is from the terminal keyboard.

The standard output of the CMD1 is passed to CMD2 as its standard input.

The standard output of the CMD2 is connected to the terminal screen.


Knowledge Point 1:pipe function

#include <unistd.h>int pipe (int fd[2]);//return value: Returns 0 if successful, or 1 if an error occurs

The process calls the pipe function to create a pipeline. The parameter of the pipe function is a pointer to an array of two integer-type file-descriptive descriptors. The function returns 0 after successfully filling in the array with two new file descriptor descriptors, assuming that failure returns-1 and sets errno to indicate the cause of the failure.

The value of errno has the following three possible types:

Emfile: The process uses too many descriptive descriptors for the file.

Enfile: The system's File table is full.

Efault: The file description descriptor is invalid.

Two newly filled file descriptive descriptors: fd[0] open for reading. FD[1] Open for writing. The output of fd[1] is the input of fd[0]. This means that all data written to fd[1] using the Write function can be read from fd[0]. The scale is as follows:

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #define MAXLINE 2048intmain (int argc, char **argv) {int fd[2];int data;char buff[maxline];const char some_data[] = "123"; memset (Buff, ' n ') , sizeof (buff)), if (pipe (FD) = =-1) {exit (exit_failure);}  Else{data = Write (fd[1], Some_data, strlen (some_data));d ata = Read (fd[0], buff, data);p rintf ("read%d bytes:%s\n", data, ) exit (exit_success);}}

Program execution Results:

[Email protected]:/work/tmp/unp$./a.out Read 3 bytes:123

The example above is a sample of the pipeline used in the same process, but is rarely used in practice. Generally, the process communicates between two different processes (usually parent-child processes). Example of a demo using pipelines between two processes:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define MAXLINE 2048intmain (int argc, char **argv) {int fd[2];int data;pid_t Child_pid;char buff[maxline];const char some_data[] = "123"; m Emset (Buff, ' n '), sizeof (buff)), if (pipe (FD) = = 0) {child_pid = fork (), if (child_pid = =-1) {fprintf (stderr, "fork error."); Exit (exit_failure);} else if (Child_pid = = 0) {close (fd[1]);  Close the write-side of the child process data = Read (Fd[0], buff, MAXLINE);//Read data from the read segment of the child process printf ("read%d bytes:%s\n", data, buff); exit (exit_success) ;} Else{close (fd[0]);//Close the read segment of the parent process data = write (Fd[1], Some_data, strlen (Some_data));//write data from the write side of the parent process printf ("wrote%d bytes\ n ", data);}} Exit (exit_success);}

The results of the program execution are:

[email protected]:/work/tmp/unp$./a.out wrote 3 Bytesread 3 bytes:123

Or

[email protected]:/work/tmp/unp$./a.out wrote 3 Bytes[email protected]:/work/tmp/unp$ read 3 bytes:123
This is due to. Assume that the parent process ends before the child process. You'll see the shell prompt. As can be seen from the demo example above, to complete the communication between parent and child processes through the pipeline, the parent process first creates a pipe and calls fork to derive a copy of itself, and then the parent process closes the read-out end of the pipeline. The child process closes the write side of the same pipeline. This provides a one-way flow of data between the parent and child processes.

When one end of a pipe is closed, the following two rules work:

1, when reading a write end has been closed pipe, after all the data is read, read returns 0 to indicate that the end of the file is reached.

2. If you write a pipe that has been closed at the read end, it generates a signal sigpipe.

If the signal is ignored or the signal is captured and returned from its handler, write returns -1,errno set to Epipe.


The two examples above are half-duplex, one-way, providing only one direction of data flow.

When a bidirectional data flow is required, you must create two pipelines. Each direction one. The actual process is for example the following:

1. Create pipeline 1 and Pipeline 2

2. Fork

3. Parent process closes the read-out end of pipe 1, closes the write end of pipeline 2

3. The child process closes the write end of the pipe 1 and closes the read-out end of the pipe 2.

after creating two pipelines, you can complete a simple client-server sample. For a demonstration sample, please click this link.


Knowledge points 2:popen and Pclose functions

the Popen and Pclose functions are not implemented by UNIX. They are provided by the standard I/O library when they are implemented: Create a pipeline, call fork to produce a child process, and close the unused end of the pipeline. Executes a shell to execute the command, and then waits for the command to terminate.

#include <stdio.h>file *popen (const char *cmdstring, const char *type);//Return value: Returns the file pointer if successful, and returns Nullint     if an error occurs Pclose (FILE *FP);//return value: cmdstring the terminating state, if an error is returned-1
The function Popen runs the fork first, then calls exec to run cmdstring, and returns a standard I/O file pointer.

Assuming that the type is "R", the file pointer is connected to the standard output of the cmdstring. Returns the file pointer when it is readable. Assuming that the type is "W", the file pointer is concatenated to the standard input of the cmdstring, which returns the file pointer when it is writable. figure Popen such as the following:

Assuming that type is "R", the output of the called program can be used by the calling program, and the calling program can use the file pointer returned by the Popen function to read the output of the called program through frequently used Stdio library functions (such as fread), assuming that the type is "w", The calling program can send data to the callee using the fwrite call, and the callee can read the data on its own standard input.


The type is a demo sample program for r such as the following:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h>intmain (int argc , char **argv) {FILE *read_fp;char buff[bufsiz + 1];int  chars_read;memset (Buff, ' n ', sizeof (buff)); read_fp = Popen (" Uname-a "," R ");//Open the pipe that is connected to the uname command. Set the pipe as readable and let READ_FP point to the command output if (read_fp! = NULL) {chars_read = fread (buff, sizeof (char), Bufsiz, READ_FP); if (chars_read > 0) printf ("Output was:-\n%s\n", Buff);p close (READ_FP); exit (exit_success);} Exit (exit_success);}
Execution Result:
Output was:-linux book-desktop 2.6.31-14-generic #48-ubuntu SMP Fri Oct 14:04:26 UTC i686 gnu/linux
the type is a demonstration sample program for w such as the following:
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h>intmain (int argc , char **argv) {FILE *fp;char buffer[bufsiz + 1];sprintf (buffer, "Once upon a time there was ... \ n"); fp = Popen ("Od-c", "W "); if (fp = NULL) {fwrite (buffer, sizeof (char), strlen (buffer), FP);p Close (FP); exit (exit_success);} Exit (exit_success);}
The program results such as the following:
0000000   o   n   c   e       u   p   o   n       a       t   i   m   e0000020       t   h   e   r   E       W   a   s   ...  \n0000037
It is also possible to implement the Client-server program like the pipe function above. Please click this link to demonstrate the sample code.
References:1, the above explanation of the diagram part: http://blog.csdn.net/to_be_it_1/article/details/28138063
2, "Linux programming" Neil Matthew&&richard stones3. Advanced Programming of UNIX environment Richard Stevenson4, "UNIX Network Programming Volume 2" Richard Stevenson





Pipeline for "UNIX network programming" interprocess communication

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.