In Linux, pipelines are frequently used communication mechanisms. In essence, an MPS queue is also a file, but it is different from a common file. The MPs queue can overcome the following two problems:
· Limit the MPs queue size. In fact, a media transcoding queue is a fixed buffer. In Linux, the buffer size is one page, that is, 4 K bytes, so that the size of the buffer does not grow as untested as the file size. Using a single fixed buffer can also cause problems. For example, the pipeline may be full when it is written. When this happens, subsequent write () calls to the pipeline will be blocked by default, wait for some data to be read to free up enough space for write () calling and writing.
· The read process may also work faster than the write process. When data of all current processes has been read, the MPs queue becomes empty. When this happens, a subsequent read () call will be blocked by default, waiting for some data to be written, which solves the problem of returning the end Of the file after the read () call.
Note: Reading data from an MPS queue is a one-time operation. Once the data is read, it is discarded from the MPs queue and space is released to write more data.
# Include <stdio. h>
# Include <unistd. h>
# Include <sys/types. h>
Int main (void)
{
Intfd [2], nbytes; pid_tchildpid;
Charstring [] = "Hello, world! \ N ";
Charreadbuffer [80]; pipe (fd );
If (childpid = fork () =-1) {perror ("fork"); exit (1 );}
If (childpid = 0) {/* Child process closes up in put side of pipe */close (fd [0]); /* Send "string" through the out put side of pipe */
Write (fd [1], string, strlen (string ));
Exit (0 );}
Else {
/* Parent process closes up out put side of pipe */close (fd [1]);
/* Readinastringfromthepipe */nbytes = read (fd [0], readbuffer, sizeof (readbuffer ));
Printf ("Receivedstring: % s", readbuffer );}
Return (0 );
}