Notes on Linux system programming: Process Communication (I.)

Source: Internet
Author: User
Tags closure

The process is simply an execution of a program, the process described here generally refers to the process running in the user state, and the different processes in the user state are isolated from each other, they must be in some way to communicate, the specific reasons are as follows:

(1) Data transfer: Sometimes a process needs to send its data to another process.

(2) resource sharing: sometimes multiple processes need to share the same resources.

(3) Notification events: Sometimes a process needs to send a message to another or a set of processes to notify them that an event has occurred.

(4) Process Control: Some processes want to have full control over the execution of another process, at which point the control process wants to be able to intercept all the actions of another process and be able to know its state changes in a timely manner.


1. Modalities for inter-process communication:

There are 6 ways to communicate between processes:

(1) pipeline communication (including famous pipes and nameless pipes)

(2) Signal communication

(3) Message Queuing communication

(4) Shared memory communication

(5) Signal Volume communication

(6) socket (socket) communication


2. Pipeline communication:

Referring to the word pipe, the person thinks you can think of it as a pipe that transports data, which links the output of one process to the input of another, a process that writes data from the end of the pipe, another process reads the data from the head of the pipe, and the data in the pipeline is removed from the pipeline after it is read by the process. Other processes will not be able to read this data again.

Pipelines provide a simple flow control mechanism that is blocked when a process attempts to read an empty pipe without data, and also if a process tries to write data to the pipeline when the capacity of the data in the pipeline is full.

There are two ways of pipeline communication: one is nameless pipeline communication, the other is famous pipeline communication, the nameless pipe can only be used for communication between parent process and child process, and the famous pipeline can be used for communication between any two processes in the same system.


2.1 Creation of nameless pipes:

Creating a nameless pipe can use the system to invoke the pipe, which is prototyped as:

int pipe (int filedis[2])

FILEDIS[2]: Pipe file descriptor, we can think of the pipe head and tail each as a file, where the end of the pipeline to write data corresponding to the file descriptor Filedis[1], to the pipe header to read the data corresponding to the file descriptor Filedis[0].

The Nameless pipeline returns 0 if it was created successfully, or 1.

The header file to be included when creating a nameless pipe using pipe system calls is:

#include <unistd.h>


2.2 Closure of nameless pipes:

Closing a nameless pipe requires only closing the two file descriptors of filedis[0] and filedis[1] with the close system call.


2.3 Unknown pipe Read and write:

Nameless pipes can only be used to communicate between parent and child processes, so when you read and write to an unnamed pipe, you typically create a nameless pipe through the pipe and then use fork to create a child process that inherits the pipeline created by the parent process.

Note: You must call the pipe function before fork to create an unnamed pipe , otherwise the child process and the parent process will each create a pipeline, the parent and child two processes do not share the same root pipe, in this case is unable to communicate.

A read-write model for nameless pipelines

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/58/C0/wKioL1S7r2aAz_FRAADFEV6I_FM558.jpg "title=" Nameless Pipe read-write model. png "alt=" wkiol1s7r2aaz_fraadfev6i_fm558.jpg "/>

2.4 Nameless Pipe Programming:

/* Create a nameless pipe in the parent process and create a child process to read the pipeline, the parent process to write the pipeline */#include  <unistd.h> #include  <sys/types.h> #include  <errno.h>  #include  <stdio.h>  #include  <string.h>  #include  <stdlib.h> int main (int argc,char*argv[]) {/* Store two file descriptors returned after creating a nameless pipe pipe_fd[0] for reading pipes, pipe _FD[1] for the write pipeline */int pipe_fd[2]; pid_t pid;char buffer_r[100]; //buffer  int real_ Read_num; memset (buffer_r,0,sizeof (Buffer_r));//The Buffer clear 0 if (pipe (PIPE_FD) <0)  //Create a nameless pipe {printf (" Create pipe failure!\n "); exit (1);} else{printf ("create pipe sucess!\n");} Pid=fork ();  if (pid==-1) {printf ("create fork process error!");} Else if (pid==0)//Sub-process  {//printf ("this is the child process!\n"); Close (pipe_fd[1]) ;  //close the pipe write end  sleep (2);  //child process sleeps 2 seconds, first let the parent process execute to the pipeline to write the data  if ((real_read_num=read ) >0)  //reads the data inside the pipe  {printf ("%d numbers&nbsP;read from the pipe is %s\n ", Real_read_num,buffer_r);} Close (pipe_fd[0]);//Sub-process read pipe end, close the pipe read end   exit (0);} else //Parent Process      {//printf ("this is the father process!\n"); Close (pipe_fd[0]);//Shut down the pipe read-end  if (write (pipe_fd[1], "hello ", 6)!=-1)//into the pipeline to write Data  {printf ("Father  process write1 hello\n ");} if (write (pipe_fd[1], "pipe!", 5)!=-1) {printf ("father process write2 pipe!\n");} Close (pipe_fd[1]);//sleep (10);//At this time the sub-process begins execution, go to the pipeline to read the data    waitpid (pid,null,0);//wait for the end of the child process     exit (0);} return 0;}


2.5 creation of famous pipelines:

Creating a named pipe can use the system call Mkfifo, which is prototyped as:

int Mkfifo (const char*pathname,mode_t mode)

Pathname: Name of the named pipe created, can contain a path, by default is the current path (a named pipe is essentially a file)

Mode_t: Properties of the created file (a named pipe is essentially a file)

When a named pipe is created successfully, the function returns 0, otherwise returns-1.

Use the MKFIFO system to create a named pipe that should contain a header file:

#include <sys/types.h>

#include <sys/stat.h>


2.6 Closure of famous pipes:

To close a named pipe, use the system call close to close the file descriptor for the named pipe.


2.7 Famous Pipeline programming:

FIFO_WRITE.C: Create a well-known pipeline and write some data inside

#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  "./myfifo"  //created by the famous pipeline is saved in the current directory     Int main (int argc,char*argv[]) {int fifo_fd; char buffer[100];//buffer   /* Create a named pipe */ if ((Mkfifo (fifo_server,o_creat| O_EXCL) (<0) && (errno!=eexist))  { printf ("Can ' t create fifo_server!\n");  exit (1);  } /* Open the famous pipe, the famous pipe is essentially a file */ fifo_fd=open (fifo_server,o_rdwr| O_nonblock);  if (fifo_fd==-1)  { printf ("open fifo_server error!\n");  exit (1);  } /* determines whether a parameter is passed into */ if (argc==1)   { printf ("please send something!\n") when the program is run );  exit (1);  } strcpy (buffer,argv[1]);  //copies the incoming parameters into the buffer   /* writes the data in the buffer into the famous pipe */ if (Write (Fifo_fd,buffer,100) ==-1)  { printf ("Write fifo_server error!maybe the fifo_server  is full!\n ");  exit (1);  } else { printf (" Write %s to the  fifo_server!\n ", argv[1]);  } close (FIFO_FD);  //close famous pipe    return 0;}

   

 #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  "./myfifo " int main (int argc,char*argv[]) {char buffer[100];int fifo_fd;int real_read_num; Fifo_fd=open (fifo,o_rdonly| O_nonblock);//Open the famous pipe  if (fifo_fd==-1) {printf ("open fifo error!\n");  exit (1);}  /* design a dead loop constantly reading data from a well-known pipe */while (1) {memset (buffer,0,100);  //the buffer Clear 0    if ((real_read _num=read (fifo_fd,buffer,100)) ==-1) {printf ("Read from fifo_server error! the fifo_ Server has no data!\n "); exit (1);} else {printf ("read %s from fifo_server!\n", buffer); sleep (1);}} Close (FIFO_FD);p ause (); unlink (FIFO); return 0;} 


Write here for the time being, to be continued.













This article is from the "Stop Thinking" blog, make sure to keep this source http://9110091.blog.51cto.com/9100091/1605410

Notes on Linux system programming: Process Communication (I.)

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.