- Piping (pipe)
Pipeline communication between UNIX and Linux processes is the most basic and easy to understand. Piping is like a water pipe, one end is injected, one end of the water, water can only flow in a direction, but not two-way flow. Pipeline is a typical one-way communication, that is, "half-duplex" in the computer network. Pipelines are also named anonymous pipes, so they can only be used between processes that have a common ancestor and are typically used to communicate between parent and child processes. Usually the parent process creates a pipeline and then fork a child process, after which the parent-child process shares the pipeline for communication. The pipeline is created by the pipe function, and the function prototype is as follows: #include <unistd.h> int pipe (int fd[2]); Successful return 0, otherwise return-1; parameter FD returns two file descriptor, Fd[0] is read, fd[1] is write, fd[1] input is fd[0] output. i.e. fd[0] corresponding to the read end, fd[1] corresponding to the write end. Illustrate the use of pipelines: simulate the client-server communication process, the parent process simulates the client, and the child process simulates the server. The server sends a string to the client and the client receives the output to the screen.
1#include <unistd.h>2#include <stdio.h>3#include <stdlib.h>4#include <sys/types.h>5#include <errno.h>6#include <string.h>7 8 intMain ()9 {Ten intfd[2]; Onepid_t childpid; A Charbuf[ -]; - -memset (BUF,0, -); the //Create a pipeline - if(pipe (FD) = =-1) - { -Perror ("pipe () error"); +Exit (-1); - } + //Create a child process AChildpid =fork (); at if(Childpid = =0) - { -printf"Server input a message:"); -scanf"%s", buf); - //Close the Read end -Close (fd[0]); inWrite (fd[1],buf,strlen (BUF)); -Exit0); to } + if(Childpid = =-1) - { thePerror ("fork () error"); *Exit (-1); $ }Panax Notoginseng //parent Process Close Write end -Close (fd[1]); theRead (fd[0],buf, -); +printf"client read a message:%s\n", buf); AWaitpid (Childpid,null,0); the return 0; +Copy the Code
View Code
Piping and FIFO