Linux_c Development (5-2) interprocess communication _ Pipeline Communication

Source: Internet
Author: User

Pipeline Communication

What is a pipe?
The pipeline is one-way, first-out, and he connects the output of one process with the input of another. One process (write process) writes data at the end of the pipeline, and another process (read process) reads the data from the head of the pipe.
Pipeline Creation
Pipelines include nameless pipes and two of known pipelines, which are used for communication between parent and child processes, which can be used for any two interprocess communication in the same system.
Nameless pipes are created by the pipe () function:
int pipe (int filedis[2]);
When a pipeline is established, he creates two file descriptors:
Filedis[0] for read pipelines, filedis[1] for writing pipelines.
Pipe off
To close the pipe, you only need to close these two file descriptors, and you can close each one by using the normal close function.
eg

#include <unistd.h>#include <errno.h>#include <stdio.h>#include <stdlib.h>intMainvoid){intpipe_fd[2];if(Pipe (PIPE_FD) <0)    {printf("Pipe creat error\n");return-1; }Else        printf("Pipe creat success\n!"); Close (pipe_fd[0]); Close (pipe_fd[1]);}

pipe reading and writing
Pipelines are used for different processes to communicate. Typically, you create a pipe first, and then you create a child process from the fork function that inherits the pipeline created by the parent process.

Precautions
Pipe () must be called before the system calls fork () otherwise the child process will not inherit the file descriptor.
Example: pipe_rw.c

#include <unistd.h>#include <sys/types.h>#include <errno.h>#include <stdio.h>#include <stdlib.h>intMain (void) {intpipe_fd[2]; Pid_pid Char buf_r[ -]; char* P_wbuf;intR_num; memset (Buf_r,0, sizeof (BUF_R));/ * Create pipeline * /    if(Pipe(PIPE_FD) <0)    {printf("Pipe creat error\n");return-1; }/* ChongBuild child process*/    if((pid=Fork())==0)    {printf("\ n");Close(pipe_fd[1]);Sleep(2);/ * Let the child process stop and let the parent process write something in the pipeline * /        if((r_num=Read(pipe_fd[0],buf_r, -)) >0)            {printf("%d number read from the pipe is %s\ n", R_num,buf_r)}Close(pipe_fd[0]);Exit(0); }Else if(pid>0)    {Close(pipe_fd[0];if(Write(pipe_fd[1],"Hello",5)!=-1)printf("Parent Write hello!\n");if(Write(pipe_fd[1],"Pipe",5)!=-1)printf("Parent Write pipe!\n");Close(pipe_fd[1]);Sleep(3);Waitpid(Pid,null,0);//Wait for the child process to endExit(0); }return 0;}

Named Pipes
Named pipes and nameless pipes are basically the same, except that nameless pipes can only be used by parent-child processes, but processes that are not related to a well-known pipeline can also exchange data.
Create

#include<sys/types.h>#include<sys/stat.h>int mkfifo(constchar* pathname,mode_t mode)

**pathname:**fifo file name
Mode: Properties
Once a FIFO is created, it can be opened with open, and general file access functions (Close, read, write, and so on) can be used for FIFO.
Operation
When FIFO is turned on, the non-blocking flag (O_nonblock) will have the following effect on subsequent reads and writes:
1. No use of O_nonblock: access requirements will be blocked.
2, use O_nonblock: Access cannot be satisfied without blocking, immediately return an error. Errno is Enxio.
Example: use Mkfifo to create a named pipe and implement communication between two processes.

/*fifo_read.c*/#include <sys/types.h>#include <sys/stat.h>#include <errno.h>#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#define FIFO "/tmp/myfifo"/* * Program Entry * */intMainintargcChar* * argv) {Charbuf_r[ -];intFdintNread;printf("Preparing for reading bytes...\n");memset(Buf_r,0,sizeof(Buf_r));/ * Open pipe * /Fd=open (fifo,o_rdonly| O_nonblock,0);if(fd==-1) {perror ("Open");Exit(1); } while(1)    {memset(Buf_r,0,sizeof(Buf_r));if(Nread=read (Fd,buf_r, -))==-1)        {if(Errno==eagain)printf("No data yet\n"); }printf("read%s from fifo\n", buf_r); Sleep1); }/ * The following three sentences will not be run, but will not affect the effect of the program running when the program is executed in the above dead loop when it receives a signal, it will end immediately without executing the following three words. These will be mentioned in the signal processing in the back, now do not understand the relationship, this problem left you to learn the signal processing to solve. */Close (FD);//Close pipePause ();/ * Pause, wait for signal * /Unlink (FIFO);//delete files}
/*fifo_write. C#include <sys/types.h>#include <sys/stat.h>#include <errno.h>#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#define Fifo_server "/tmp/myfifo"/* * Program Entry **/intMainintArgc,char**argv) {intFd Char w_buf[ -];intNwrite;/ * Create a named pipe * /    if((Mkfifo (fifo_server,o_creat| o_excl| O_RDWR) <0) && (errno!=eexist)) {printf("Cannot create fifoserver\n"); }    /* PlayOpen pipe*/Fd=Open(Fifo_server,o_wronly | O_nonblock,0);if(fd==-1) {perror ("Open");Exit(1); }    /* intoReference detection*/    if(argc==1)    {printf("Please send something\n");Exit(-1); } strcpy (w_buf,argv[1]);/ * Write data to pipe * /    if((nwrite=Write(Fd,w_buf, -))==-1)    {if(Errno==eagain)printf("The FIFO has not been read yet. Please try later\n "); }Else{printf("Write %s to the fifo\n", W_BUF); }Close(FD);//Close pipereturn 0;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Linux_c Development (5-2) interprocess communication _ Pipeline 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.