Linux Process Communication-pipelines and linux Process Pipelines

Source: Internet
Author: User

Linux Process Communication-pipelines and linux Process Pipelines

Inter-process Communication (IPC: Inner Proceeding Communication)

A process is an imaginary way for the operating system to realize that the program exclusively runs the system. It is an abstract representation of the processor, primary storage, and I/O devices. Each process is an independent Resource Management Unit. Each process sees the illusion that it exclusively uses the system. Therefore, each process cannot directly access the resources of the other process, the special process communication mechanism provided by the operating system is required for information interaction between different processes.

Communication between processes is physically divided into processes on the same host and processes on different hosts. Data Interaction, synchronous communication, and asynchronous communication can be divided into communication content methods.

Shows the communication methods between processes in Linux.


The preceding two types of data are divided by physical and content:

(1) Data Interaction Between processes on the same host: Unknown pipelines (PIPE), famous pipelines (FIFO), Message queues (Message Queue), and Shared Memory (Shared Memory ).

(2) synchronous communication mechanism between processes on the same host: Semaphore ).

(3) asynchronous communication mechanism between processes on the same host: Signal (Signal ).

(4) process data interaction between different hosts: Socket and Remote Call RPC (Remote Procedure Call ).


Pipeline Communication

Pipelines can also be dividedUnknown MPs queueAndNamed PipeThe two are used differently.

Nameless pipeline PIPE: it is mainly used for communication between kinship processes. The communication of nameless pipeline is one-way and can only be from one segment to another. The Nameless pipeline is temporary, after the communication is completed, it will automatically disappear. Generally, a sub-process is created to inherit the file descriptor of the parent process, so that the sub-process can communicate with the parent and child processes, if you want to use an unknown pipeline for communication, you need to use another file descriptor transfer mechanism.

Famous pipeline FIFO: A famous pipeline is a special file that actually exists. Using a famous Pipeline, you can achieve data interaction between any process on the same host.


In ShellUnknown MPs queue

In the Shell command line, the unnamed pipe is implemented by the pipeline character "|". The following shell command passes the cat command output to the grep command input through the pipeline.


An unknown pipeline is a special file, which means you can operate an unknown pipeline like an operating file. An unknown pipeline corresponds to a special memory space in the kernel, this memory space is managed by the operating system and invisible to users. It can only be accessed by system calls in user space applications. In this memory space, the information sent by a process to another process is temporarily stored in the cyclic queue mode, and the corresponding space is automatically released after the communication is complete.


Unknown pipelines in Linux C Programming

1. Create an unknown MPs queue

You must use the pipe (int _ pipedes [2]) function to create an unknown pipeline. The parameter of this function is an integer array containing two elements. If the operation is successful, this integer array stores the file descriptors of the read end and the write end of the unknown pipeline respectively. Using these two read and write file descriptors, we can perform read and write operations on the unknown pipeline like reading and writing files. If the pipe () function fails to be called,-1 is returned.


2. Read and Write unknown Pipelines

The following program is completed in a program, that is, a process acts as both a read process and a write process.

# Include <stdio. h> # include <unistd. h> # include <string. h> int main () {int p [2]; char * str = "HelloWorld"; // The string char buf [128] to be written to the unknown pipeline; // read the buffer memset (buf, '\ 0', 128) when the unknown MPs queue is read; // clear the buffer if (pipe (p) =-1) {printf ("function pipe () CILS failed. "); return-1;} write (p [1], str, strlen (str); // write the read (p [0], buf, strlen (str); // read the unnamed pipeline printf ("% s \ n", buf); // print the read content return 0 ;}

The following program simulates the communication between parent and child processes with kinship. The child process sends a string str to the parent process, following the above steps to create a pipeline and then create a child process, in this way, the process will copy the pipeline file descriptor of the parent process.

# Include <stdio. h> # include <unistd. h> # include <string. h> int main () {int p [2]; int pid; char * str = "HelloWorld"; char buf [128]; memset (buf, '\ 0 ', 128); if (pipe (p) =-1) {printf ("function pipe () CILS failed. "); return-1;} if (pid = fork () =-1) // create a sub-process {printf (" function fork () CILS failed. \ n "); return-1;} else if (pid = 0) // In the sub-process {printf (" In sub: pid = % d \ n ", getpid (); write (p [1], str, strlen (str )); // write str} else {// In the parent process printf ("In father: pid = % d \ n", getpid ()); read (p [0], buf, strlen (str); // read the unnamed pipeline printf ("In father: buf = % s \ n", buf );}}

Output results of the above program:



Note: The read and write methods of read and write pipelines are blocking by default. When the pipeline is read, but there is no data in the pipeline, and no process writes data to the write end, read operations may be blocked. Similarly, if you write data to the pipeline, but the pipeline is full (the pipeline is a special memory space file, and the default size is PIPE_BUF, generally 4096 bytes), write operations will be blocked. In addition, if the read end is closed when the pipeline is written, the write operation will receive the SIGPIPE signal, and the write function returns-1.


Named Pipe

Named Pipe is a type of actually existing file. In shell, we can use the mknod command to create a named pipe. The following is the usage of mknod and a p_file file is created using mknod, the file type of this file is p.


Named pipelines in Linux C Programming

1. Create a named pipe

In programming, you can use the mkfifo (char * path, _ mode_t _ mode) function to create a named pipe. mkfifo has two parameters. The first one is to specify the name of the named pipe to be created, the second is the generated named pipeline file mode.


2. read/write naming Pipeline

Like the unnamed pipe, the named pipe is still a memory segment managed by the kernel space. However, before using the write and read functions, you must use the open function to open the named pipe file.

The following program uses a named pipeline for communication between two unrelated processes.

The write process source code is as follows:

#include<stdio.h>#include<unistd.h>#include<string.h>#include<fcntl.h>int main(){int fd;int res;char *str = "HelloWorld";res = mkfifo("myfifo",0766);if(res != 0){printf("function nkfifo() calls failed.");return -1;}fd = open("myfifo",O_WRONLY); //create fifo file named "myfifo"if(fd == -1){printf("function open() calls failed.");return -1;}printf("This proceeding id =%d, fifo file file ID=%d\n",getpid(),fd);res = write(fd,str,strlen(str));  //write to fifo file, This will be blocking if no readif(res == -1){printf("function write() calls failed.");return -1;}printf("write ok.\n");close(fd);return 0;}

The source code for reading the MPs queue program is as follows:

#include<stdio.h>#include<unistd.h>#include<string.h>#include<fcntl.h>int main(){int fd;int res;char buf[4096];memset(buf,'\0',4096);fd = open("myfifo",O_RDONLY);  //open fifo fileif(fd == -1){printf("function open() calls failed.");return -1;}printf("This proceeding id=%d, fd=%d\n",getpid(),fd);read(fd,buf,sizeof(buf)); //read fifo into buffer, This is a blocking methodprintf("read : buf=%s\n",buf);close(fd);return 0;}

You need to run the write process first. Because you need to create an MPS queue file, the write method will be blocked because no read is associated with the MPs queue. continue to run the read process on another terminal, the read process can read the data sent by the write process, and the blocking of the write process will be lifted.



Summary:

The unnamed pipeline is mainly used for communication between parent-child processes with kinship. It is temporary. You need to create an pipeline first and then create a sub-process. pipelines are unidirectional. To achieve bidirectional communication, two pipelines are required. The named MPs queue is an existing file that needs to be opened before use. The default read and write operations of the MPs queue are blocking.




Process Creation and inter-process communication in Linux

# Include <stdio. h>
# Include <unistd. h>
# Include <string. h>
# Include <stdlib. h>

Int main ()
{
Int fd [2], pid, len;
Char inpipe [100], outpipe [100];

Pipe (fd );

Pid = fork ();

If (pid = 0)
{
/* First child */
Close (fd [0]);
Strcpy (outpipe, "The first child process is sending message! ");
Lockf (fd [1], 1, 0 );
Write (fd [1], outpipe, 100 );
Lockf (fd [1], 0, 0 );
Exit (0 );
}

Pid = fork ();
If (pid = 0)
{
/* 2nd child */
Close (fd [0]);
Strcpy (outpipe, "The second child process is sending message! ");
Lockf (fd [1], 1, 0 );
Write (fd [1], outpipe, 100 );
Lockf (fd [1], 0, 0 );
Exit (0 );
}

/* Parent */
Close (fd [1]);
Len = read (fd [0], inpipe, 100 );
Printf ("RECV: % s \ n", inpipe );

Len = read (fd [0], inpipe, 100 );
Printf ("RECV: % s \ n", inpipe );

Wait (NULL );
Wait (NULL );
Return 0;
}

Linux inter-process communication methods

For more information about pipelines, famous pipelines, semaphores, message queues, signals, shared memory, and sockets, see the second volume of UNIX network programming for inter-process communication. Author: W. Richard Steven s

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.