Inter-process communication between Linux

Source: Internet
Author: User

Linux Pipelines

A pipeline is a communication device that allows one-way communication. The data is written from one end of the pipe and read out from the other end of the pipe. Pipelines are serial devices, and data is always read in the order in which they are written. Typically, a pipeline is used for two different threads of the same process or to pass between parent and child processes.

in the Shell , use | symbol creation Pipeline. For example, the following Shell command will cause the shell to create two sub-processes, respectively, for ls and less command:

% ls | Less

Shell A pipeline is also created to connect ls standard output of child processes and Less the standard input for the process. the file name listed by LS is transferred to less , and its order is consistent with its direct display in the terminal.

The data capacity of the pipeline is limited. If the write process reads data faster than the read process and the pipeline cannot store too much data, the write process will block until more capacity is available. As a result, the pipeline automatically synchronizes two processes.

Creating Pipelines

to create a pipeline, call the Pipe command. Specifies an array of integers with a size of 2. the Pipe call places the read file descriptor in position 0 of the array , and the write file descriptor is stored in the array number 1 . For example, consider the following code:

int Pipe_fds[2];int read_fd;int write_fd;pipe (PIPE_FDS); read_fd = PIPE_FDS[0];WRITE_FD = Pipe_fds[1];

through WRITE_FD the data written by the file descriptor can be READ_FD The file descriptor is read back.

Inter-parent interprocess communication

through Pipe The file descriptor created is valid only in the current process and its child processes. The process file descriptor cannot be passed to the unrelated process; However, when the process calls fork , the file descriptor is copied to the child process. Therefore, pipelines can only connect to related processes.

fork Create a child process. The child process inherits the pipe file descriptor of the parent process. The parent process writes the string in the pipeline, and the child process reads it out. This program uses fdopen file* The file stream for span style= "". Because using streams instead of file descriptors, let's use the high-level standard c i/o library functions, such as printf Fgets

#include <stdlib.h> #include <stdio.h> #include <unistd.h>/* Write COUNT copies of MESSAGE to STREAM, Pau Sing for a second * between each. */void writer (const char *message, int count, FILE *stream) {for (; count > 0;--count) {/* Write the MESSAG E to the stream, and send it off immediately.        */fprintf (stream, "%s\n", message);        Fflush (stream); /* Snooze a while.    */Sleep (1); }}/* Read random strings from the stream as long as possible.    */void Reader (FILE *stream) {char buffer[1024]; /* Read until we hit the end of the stream. Fgets reads until * Either a newline or the end-of-file.         */while (!feof (stream) &&!ferror (stream) && fgets (buffer, sizeof (buffer), stream)! = NULL) Fputs (buffer, stdout);}    <pre name= "code" class= "CPP" >int main () {int fds[2];    pid_t pid; /* Create a pipe. File descriptors for the ends of the * pipe is placed in FDS.   */pipe (FDS); /* Fork a child process.        */if (PID = fork ()) = = 0) {FILE *stream; /* the child process. Close our Copy the write end of * The file descriptor.        */Close (fds[1]);        stream = Fdopen (Fds[0], "R");        Reader (stream);    Close (Fds[0]);        } else if (PID = =-1) {} else {/* This is the parent process. */FILE *stream; /* Close Our copy of the read end of the the file descriptor.        */Close (fds[0]);        stream = Fdopen (Fds[0], "R");        Reader (stream);    Close (fds[1]); } return 0;}

in the Main the start of the function, the declaration size is 2 An array of integers. creates a pipe through the pipe and places the read-write file descriptor in the array. The program then creates the child process. After the read pipeline is closed, the parent process begins writing a string to the pipeline. The child process reads the string from the read pipeline after the write pipeline is closed.

Note that the writer each time the function writes data, the parent process calls the Fflush refreshes the pipeline. Otherwise, the string may not be sent out by the pipeline.

when calling ls | less command, there are two processes: a ls child process and a Less child process. Both processes inherit the pipe file descriptor, so they can communicate through the pipeline. In order for unrelated processes to communicate, FIFO can be used instead.

REDIRECT standard input, output, and error outputs

Typically, you need to create a child process and set one end of its pipeline as standard input or output. Using the dup2 function, you can equate a file descriptor with another file descriptor. For example, in order to redirect the input of the FD file descriptor to standard input, you can use the following methods:

Dup2 (Fd,stdi_fileno);

Constants Stdin_fileno represents a standard input file descriptor with a value of 0 . The function closes the standard input and then re-opens the standard input as a copy of FD, so that the two file descriptors can be exchanged for use. equated file descriptors share the same file position and the sameset of file status flags. Thus, characters read from FD is not reread fromstandard input.

Popenand thePclose

pipelines are typically used to send or receive data to a program's child processes. the Popen and pclose functions simplify calls to pipe,fork, dup2 , exec and the Fdopen .

#include <stdio.h> #include <unistd.h>int main () {    FILE *stream = Popen ("Sort", "w");    fprintf (Stream, "This is a test.\n");    fprintf (Stream, "Hello, world.\n");    fprintf (Stream, "My Dog has fleas.\n");    fprintf (Stream, "This program is great.\n");    fprintf (Stream, "one fish, and the other fish.\n");    return Pclose (stream);}

Popen function to create a child process execution Sort command. The second parameter "W" indicates that the process wants to write data to the child process. The return value of the Popen function is one end of the pipeline, and the other end is used to connect the standard input of the child process. After the write data is complete, call the pclose function to close the stream of the child process, wait for the process to terminate, and return the status value.

function Popen execution of the first parameter is similar to the execution of a Shell command. the shell searches the PATH environment variable in the usual way to Find the program execution. If the second argument is "R", the function returns the standard output stream of the child process so that the parent process can read the output. If the second parameter is "W", the function returns the standard input stream of the child process, and the parent process can write the data. If an error occurs, the function popen returns a NULL pointer.

called Pclose Close by Popen the returned stream. After the specified stream is closed,pclose waits for the child process to terminate.

FIFOs

FIFO ( FIFO file is a pipe that has a name in the file system. Any process can turn the FIFOon or off, and processes on both sides of the pipeline do not need to be related to each other. FIFOs are also commonly referred to as named pipes.

to create a named pipe, you can use the Mkfifo command. Specify the path to the named pipe on the command line. For example, create a /tmp/fifo named pipe:

% mkfifo/tmp/fifo% ls–l/tmp/fifoprw-rw-rw-   1  Samuel  users 0 Jan 14:04/tmp/fifo

ls the first character of a command output is P , which means that the file is actually FIFO (Named pipes) file. In a window, read the FIFO using the following command :

% Cat </tmp/fifo

in another window, use the following command to FIFO Write Data:

% Cat >/tmp/fifo

Next, enter some text. Each time the Enter key is pressed , the text content of a line is sent through a FIFO and displayed in the first window. Close the FIFO by pressing CTRL+D in the second window . Remove the FIFO with the following command :

% Rm/tmp/fifo

1 creating a FIFO

through Mkfifo to create a programmatic way FIFO . The first parameter is the path created by the FIFO, and the second parameter specifies the owner, group, and permissions for the pipeline. Because the shutdown must have both read and write, the permissions have to include read and write permissions. If the pipeline cannot be created (for example, if the file already exists),mkfifo returns -1. If you call mkfifo, you need to include <sys/types.h> and <sys/stat.h> .

2 access FIFO

the FIFO Access is like accessing a normal file. With FIFO Communication, a program must be opened in writing and another program opened in a read-only manner. Low-level I/O functions or Standard C Library I/O functions can be used.

For example, using low-level I/O to FIFO You can use the following code to write the data:

int fd = open (Fifo_path, o_wronly); write (fd, data, data_length); close (FD);

Use standard C Library I/O function Read FIFO , you can use the following code:

FILE *fifo = fopen (Fifo_path, "R"), FSCANF (FIFO, "%s", buffer), fclose (FIFO);

a FIFO There can be multiple read or write processes. Bytesfrom Each writer is written atomically up to a maximum size of pipe_buf (4KBon Linux). Chunks from simultaneous writers can be interleaved. Similar rulesapply to simultaneous reads.

3 different from Windows Named pipes

Win32 pipelines in the operating system are similar to Linux in the pipeline. The main differences are focused on named pipes, and for Win32 , named pipes are more like sockets. the Win32 named pipe can be disconnected over a network by a computer's process. Similarly,Win32 allows multiple read and write connections to the same named pipe, does not have cross-data, and supports bidirectional communication.




Inter-process communication between Linux

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.