Home > php教程 > PHP开发 > body text

Linux C Programming - Pipes

高洛峰
Release: 2016-12-13 11:37:19
Original
1479 people have browsed it

In Linux, a pipe is also a kind of file, but it is special. We can use the pipe function to create a pipe, and its prototype is declared as follows:

#inlcude

int pipe(int fields[2] );

In fact, it is equivalent to a communication buffer, fields[0] is used for reading, and fields[1] is used for writing. In the following example, a pipe is created as a communication buffer. The parent process creates a child process. The child process writes a string into the pipe through the fields[1] descriptor of the pipe, while the parent process uses the fields[1] of the pipe. 0] Read this string from the pipe and display it:

#include
#include
#include
#include #include
#include
#include

#define BUF_SIZ 255 // message buffer size

int main(int argc , char **argv)
{
char buffer[BUF_SIZ + 1];
int fd[2];

// receive a string as parameter
if (argc != 2)
{
fprintf (stderr, "Usage : %s stringna", argv[0]);
exit(1);
}

// create pipe for communication
if (pipe(fd) != 0)
{
fprintf(stderr, "C reate pipe error : %sna", strerror(errno));
exit(1);
}

if (fork() == 0) // in child process write msg to pipe
{
close(fd[0]); "Printf (" Child%LD WRITE to PIPENA ", Getpid ());
Snprintf (buffer, buf_siz,"%s ", argv [1]);
Write (fd [1], buffer, strlen (buffer)) ; T Printf ("Child%ld quit.na", getpid ());
}
else // in Parent Process, Read MSG from Pipe
{
Close (fd [1]); read from pipena", getpid());
memset(buffer, '

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template