Pipes between processes in C
A pipe is a pair of descriptors: the child writes, the parent reads.
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
int fds[2];
if (pipe(fds) != 0) {
perror("pipe");
return 1;
}
pid_t pid = fork();
if (pid == 0) {
close(fds[0]);
const char *message = "from the child\n";
write(fds[1], message, strlen(message));
close(fds[1]);
_exit(0);
}
close(fds[1]);
char buffer[64];
ssize_t n = read(fds[0], buffer, sizeof buffer - 1);
if (n > 0) {
buffer[n] = '\0';
printf("parent read: %s", buffer);
}
close(fds[0]);
wait(NULL);
return 0;
}
How it works
- Each side closes the end it does not use.
- The reader sees end of file once every writer has closed.
- Forgetting to close is the classic reason a read hangs.
Keywords and builtins used here
NULLcharconstifintmainpid_treturnsizeofssize_tvoid
The run, in numbers
- Lines
- 32
- Characters to type
- 515
- Tokens
- 183
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 105 seconds.
Step 3 of 4 in Processes & signals, step 9 of 14 in Systems programming.