interprocess communication (1)---anonymous pipes and Named pipes

Source: Internet
Author: User
Tags semaphore stdin

pipelines are a basic way of interprocess communication, and pipelines are divided into two types, anonymous pipes and named Pipes, first of all . name Pipe

Anonymous pipe (pipe)

#include <unistd.h>int pipe (int filedes[2]);

When the pipe is called, a buffer is opened in the kernel, using fileds[0] as the output, fileds[1] is the write port, and the call returns 0 on success, and 1 when the failure occurs;

Features of pipe:

1: It can only communicate between the processes that are related to the relationship.

2: It can only be a single communication, one process read, the other can only write.

3: It is a streaming service.

4: Its life cycle follows the life cycle of the process.

Pipe is used in four special cases,

1> (code below):

If all file descriptors pointing to the pipe write end are closed (the reference count for the pipe write is equal to 0), there is still

The process reads the data from the read-side of the pipeline, and the remaining data in the pipeline is read, and read again returns 0, like

Read the end of the file.

  1  #include <stdio.h>  2  #include <stdlib.h>  3 # include<unistd.h>  4  #include <sys/types.h>  5  #include <string.h >  6 int main ()   7 {  8     int  status=0;  9     int _pipe_id[2]; 10      if (Pipe (_pipe_id) <0)  11     { 12          perror ("pipe");  13         exit (1);  14     } 15     pid_t id=fork ();  16      if (id<0)  17     { 18          perror ("fork"); 19     } 20      else if (id==0)  21     { 22         close (_ Pipe_id[0]);  23         char my_buf[]= "Hello world "; 24         int count=10; 25          while (count--) { 26              //if (count<5)  27         //   { 28                  write (_pipe_id[1],my_buf,strlen (my_buf)); 29          //  } 30              sleep (1); 31         } 32          close (_pipe_id[1]);  33     } 34     else  35     { 36         close (_ PIPE_ID[1]);  37         char my_buf[1024]; 38          int count=100; 39          while (count--)  40         {  41             memset (my_buf, ' I ', sizeof (MY_BUF));  42             ssize_t  size= read (_pipe_id[0],my_buf,sizeof (my_buf)); 43                  printf ("%d,%s\n", Size,my_buf); 44         &nBSP;}  45             pid_t _wait_pid= Waitpid (id,null,0);  46             if (_ wait_pid<0)  47             { 48                  return  1; 49             } 50      } 51     return 0; 52 }

The output is the string that reads the sub-process into the pipeline every second, read keeps returning zero, and then ends

2> (The code removes the comment from the above code)

If there is a file descriptor pointing to the pipe write side is not closed (the reference count for the pipe write is greater than 0), and the

Process also does not write data to the pipeline, there is a process reading the data from the pipe, then the remaining number in the pipeline

Read, and then read again blocks until the data is readable in the pipeline and is returned.

3>(code below to change the parent process code above)

If all the file descriptors that point to the pipe read end are closed (the reference count for the pipe read equals 0), then there is a

To write to the pipeline, the process receives a signal sigpipe (after the reader closes, two consecutive instructions will return the abnormal semaphore), which usually causes the process to terminate unexpectedly.

 38         int count=5; 39          while (count--)  40          { 41             memset (My_buf, ' ', sizeof (MY_BUF));  42             ssize_ T size= read (_pipe_id[0],my_buf,sizeof (my_buf)); 43              printf ("%d,%s\n", Size,my_buf); 44          } 45         close (_pipe_id[0]);  46              pid_t _wait_pid=waitpid (ID, &status,0);  47             printf (" status=%d\n ",status&0xFF);  48     } 

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7E/D6/wKiom1cJ7rjRpRR3AABHfYoycKg849.png "title=" Untitled. png "alt=" Wkiom1cj7rjrprr3aabhfyoyckg849.png "/> output saved as shown on the left, the Semaphore 13 is sigpipe.

4>

If there is a file descriptor pointing to the pipe read side is not closed (the reference count of the pipe read is greater than 0), and the holder of the pipe read

process does not read the data from the pipeline, then there is a process to write the data to the pipe, then when the pipe is written full Write again will block until there is an empty position in the pipeline before writing the data and returning

Child processes are as follows

24         int count=0; 25          while (1) { 26              count++; 27              ssize_t size=write (_pipe_id[1],my_buf,strlen (my_buf)); 28              if (size>0)  29              { 30              printf ("child%d\n", Count);      ; 31              } 32              else{ 33                  printf ("child_count=%d,size=%d\n", Count,size); 34                  sleep (3); 35              }    36          }    37     }

 38     else 39     { 40              sleep (1); 41          close (_pipe_id[1]);  42         char  my_buf[1024]; 43         int count=15; 44          while (count--)  45          { 46  47                  memset (my_buf, ' + ', sizeof (MY_BUF)); 48                  ssize_t size= read (_ Pipe_id[0],my_buf,sizeof (MY_BUF)); 49                  printf ("%d,%s\n", Size,my_buf); 50                  sleep (5);  51         }

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7E/D3/wKioL1cJ-p6Rf0q7AAAlvJq_z3w875.png "title=" Untitled. png "alt=" Wkiol1cj-p6rf0q7aaalvjq_z3w875.png "/> in my running environment (virtual machine CentOS), a maximum of 70kb of content is written to the pipeline at a time, The parent process then reads the data before it begins to store.


Named Pipes (FIFO)

Because anonymous pipelines can only communicate between processes that are related to one another, a named pipe is introduced, and a named pipe is actually used to communicate between the two parties by creating a file that is accessible to both parties. One is to call the Mknod or Mkfifo function in the program to create a named pipe, and the other is to establish a named pipe interactively under the shell.

#include <sys/types.h> #include <sys/stat.h>int mknod (const char *path,mode_t mod,dev_t dev); int Mkfifo ( const char *path,mode_t mode);

Function arguments The first is the path, the second is the permission, which is typically created using s_ififo|0666.

server.c

  #include <stdio.h>  2  #include <sys/types.h>  3  #include <sys/ stat.h>  4  #include <string.h>  5  #include <error.h>  6   #include <fcntl.h>  7  #include <unistd.h>  8  #define  _path_   "./.tmp_fifo"   9  10 int main ()  11 { 12      umask (0);  13     if (Mkfifo (_path_,0666| S_IFIFO) <0)  14     { 15          perror ("Mkfifo"); 16     } 17     char  My_buf[1024]; 18     memset (my_buf, ' + ', sizeof (MY_BUF)); 19          int fd=open (_path_,o_wronly); 20           21             if (fd<0)  22              {     23                       Perror ("open");  24             } 25   26     while (1)  27     { 28          printf ("Please write:"); 29          fflush (stdout); 30          Fgets (my_buf,sizeof (my_buf) -1,stdin); 31         int  Size=write (Fd,my_buf,strlen (MY_BUF));  32     if (size<0)  33      { 34         printf ("write error!\n"); 35          break; 36     } 37      if (strncmp (My_buf, "Quit", 4) ==0)  38     { 39          break; 40     } 41      } 42     close (FD);  43     return  0;      44     }

client

 1  #include <stdio.h>  2  #include <sys/types.h>  3  #include <sys/stat.h>  4  #include <string.h>  5  #include <error.h>   6  #include <fcntl.h>  7  #include <unistd.h>  8    9  #define  _PATH_  "./.tmp_fifo"  10  11 int main ()  12 {  13     int fd=open (_path_,o_rdonly);  14     if (FD <0)  15     { 16          Perror ("open");  17     } 18     char my_buf[ 1024]; 19     memset (my_buf, ' + ', sizeof (MY_BUF)); 20          while (1)  21         {  22         int size=read (fd,my_buf,sizeof (MY_BUF)-1); 23                       Perror ("open");  24             } 25   26     while (1)  27     { 28          printf ("Please write:"); 29          fflush (stdout); 30          Fgets (my_buf,sizeof (my_buf) -1,stdin); 31         int  Size=write (Fd,my_buf,strlen (MY_BUF));  32     if (size<0)  33      { 34         printf ("write error!\n") ;  35         break; 36     } 37      if (strncmp (My_buf, "Quit", 4) ==0)  38     { 39          break; 40     } 41      } 42     close (FD);  43     return  0; 44 }


This article is from the "Traces" blog, be sure to keep this source http://wpfbcr.blog.51cto.com/10696766/1762380

interprocess communication (1)---anonymous pipes and Named pipes

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.