Creating a Pipe in C

What is a pipe in C?

A pipe in C is a unidirectional data channel that can be used for interprocess communication. One process may write to the pipe, while another process may read from it. This was you can communicate from one process to another through this channel.

How do I use a pipe in C?

Here is a quick example from the pipe linux man page of setting up a pipe in C, with a parent process writing to the pipe and a child process reading from it.

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
 
int
main(int argc, char *argv[])
{
	int pipefd[2];
	pid_t cpid;
	char buf;
 
	if (argc != 2) {
		fprintf(stderr, "Usage: %s \n", argv[0]);
		exit(EXIT_FAILURE);
	}
 
	if (pipe(pipefd) == -1) {
		perror("pipe");
		exit(EXIT_FAILURE);
	}
 
	cpid = fork();
	if (cpid == -1) {
		perror("fork");
		exit(EXIT_FAILURE);
	}
 
	if (cpid == 0) {    /* Child reads from pipe */
		close(pipefd[1]);          /* Close unused write end */
 
		while (read(pipefd[0], &amp;buf, 1) &gt; 0)
			write(STDOUT_FILENO, &amp;buf, 1);
 
		write(STDOUT_FILENO, "\n", 1);
		close(pipefd[0]);
		_exit(EXIT_SUCCESS);
 
	} else {            /* Parent writes argv[1] to pipe */
		close(pipefd[0]);          /* Close unused read end */
		write(pipefd[1], argv[1], strlen(argv[1]));
		close(pipefd[1]);          /* Reader will see EOF */
		wait(NULL);                /* Wait for child */
		exit(EXIT_SUCCESS);
	}
}

Creating a Pipe in C

What is a pipe in C?

A pipe in C is a unidirectional data channel that can be used for interprocess communication. One process may write to the pipe, while another process may read from it. This was you can communicate from one process to another through this channel.

How do I use a pipe in C?

Here is a quick example from the pipe linux man page of setting up a pipe in C, with a parent process writing to the pipe and a child process reading from it.

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
 
int
main(int argc, char *argv[])
{
	int pipefd[2];
	pid_t cpid;
	char buf;
 
	if (argc != 2) {
		fprintf(stderr, "Usage: %s \n", argv[0]);
		exit(EXIT_FAILURE);
	}
 
	if (pipe(pipefd) == -1) {
		perror("pipe");
		exit(EXIT_FAILURE);
	}
 
	cpid = fork();
	if (cpid == -1) {
		perror("fork");
		exit(EXIT_FAILURE);
	}
 
	if (cpid == 0) {    /* Child reads from pipe */
		close(pipefd[1]);          /* Close unused write end */
 
		while (read(pipefd[0], &amp;buf, 1) &gt; 0)
			write(STDOUT_FILENO, &amp;buf, 1);
 
		write(STDOUT_FILENO, "\n", 1);
		close(pipefd[0]);
		_exit(EXIT_SUCCESS);
 
	} else {            /* Parent writes argv[1] to pipe */
		close(pipefd[0]);          /* Close unused read end */
		write(pipefd[1], argv[1], strlen(argv[1]));
		close(pipefd[1]);          /* Reader will see EOF */
		wait(NULL);                /* Wait for child */
		exit(EXIT_SUCCESS);
	}
}