Linux-pipeline pipe

Source: Internet
Author: User

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 );

}

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.