In the previous article that said the pipe is anonymous pipe (pipe), this article is another way of communicating between processes, named pipe (FIFO)
The life cycle of an anonymous pipeline with a process
The life cycle of a named pipe comes with the system
Anonymous pipelines cannot communicate between unrelated processes (such as parent-child, sibling processes), and named pipes solve this problem
It is a special file that can communicate between any process
There are two ways to create a pipeline: one is to build a named pipe interactively under the shell, and the second is to Mkfifo () through the function.
A. Shell mode allows you to create pipelines through the Mknod and MKFIFO commands
Two. Create with Mkfifo ()
#include <sys/types.h>
#include <sys/stat.h>
int Mkfifo (const char *pathname, mode_t mode);
Pathname to create the full pathname of the pipeline, MoD is the access mode and permissions for the named pipe that is created (Umask affects its permissions)
The code is as follows: (server is read, client is write)
Server Read-only:
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <string.h>int main () { umask ( 0); if (Mkfifo ("./.fifo", s_ififo | 0666) <0) {//failed perror ("Mkfifo"); return -1; } int _fd=open ("./.fifo", O_RDONLY) ; if (_fd==-1) { perror ("open"); return -1; } while (1) { char buf[1024]; memset (buf, ' + ', sizeof (BUF)); ssize_t _Size=read (_fd,buf,sizeof (BUF)); if (_size<=0) { printf ("client has quit or error\n "); break; } else if (_size>0) { buf[_size-1]= '; printf ("client is say# %s\n", buf); } } close (_FD); return 0;}
Client Write-side:
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <string.h>int main () { int _fd=open ("./.fifo", o_wronly); if (_fd==-1) { perror ("open"); return -1; } while (1) { char buf[1024]; memset (buf, ' + ', sizeof (BUF)); printf ("Please write your words:"); fflush (stdout); if (Read (0,buf,sizeof (BUF)-1) <0) { perror ("read"); return -1; } ssize_t _size=write (_fd,buf,strlen (BUF)); if (_size<0) { perror (" Write "); return -1; } } close (_FD); return 0;}
The results of the operation are as follows:
650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/7E/D8/wKiom1cKJW6T3-02AAAneuLQp8c377.png "title=" 1.png " alt= "Wkiom1ckjw6t3-02aaaneulqp8c377.png"/>
When the client sends a message, the server side returns immediately, and when the client exits, the server outputs "client has quit or error"
Named Pipes for interprocess communication