I know how to create one pipe in Linux with C that looks like cat /tmp/txt |grep foo
, but I have problems implementing multiple chained pipes like this cat /tmp/1.txt | uniq -c | sort
. How to do it with C using pipe()
in Linux?
UPDATE: I've figured it out. Here's the code if anybody ever have the same question:
enum PIPES {
READ, WRITE
};
int filedes[2];
int filedes2[2];
pipe(filedes);
pipe(filedes2);
pid_t pid = fork();
if (pid == 0) {
dup2(filedes[WRITE], 1);
char *argv[] = {"cat", "/tmp/1.txt", NULL};
execv("/bin/cat", argv);
exit(0);
}
else {
close(filedes[1]);
}
pid = fork();
if (pid == 0) {
dup2(filedes[READ], 0);
dup2(filedes2[WRITE], 1);
char *argv[] = {"uniq", "-c", NULL};
execv("/usr/bin/uniq", argv);
}
else {
close(filedes2[1]);
}
pid = fork();
if (pid == 0) {
dup2(filedes2[READ], 0);
char *argv1[] = {"sort", NULL};
execv("/usr/bin/sort", argv1);
}
waitpid(pid);