Skip to content

Instantly share code, notes, and snippets.

@aspatic
Forked from iomonad/pipex.c
Created October 21, 2019 15:28
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save aspatic/93e197083b65678a132b9ecee53cfe86 to your computer and use it in GitHub Desktop.
Save aspatic/93e197083b65678a132b9ecee53cfe86 to your computer and use it in GitHub Desktop.
Multiple pipes in C
/*
** pipex.c - multipipes support
*/
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
/*
* loop over commands by sharing
* pipes.
*/
static void
pipeline(char ***cmd)
{
int fd[2];
pid_t pid;
int fdd = 0; /* Backup */
while (*cmd != NULL) {
pipe(fd); /* Sharing bidiflow */
if ((pid = fork()) == -1) {
perror("fork");
exit(1);
}
else if (pid == 0) {
dup2(fdd, 0);
if (*(cmd + 1) != NULL) {
dup2(fd[1], 1);
}
close(fd[0]);
execvp((*cmd)[0], *cmd);
exit(1);
}
else {
wait(NULL); /* Collect childs */
close(fd[1]);
fdd = fd[0];
cmd++;
}
}
}
/*
* Compute multi-pipeline based
* on a command list.
*/
int
main(int argc, char *argv[])
{
char *ls[] = {"ls", "-al", NULL};
char *rev[] = {"rev", NULL};
char *nl[] = {"nl", NULL};
char *cat[] = {"cat", "-e", NULL};
char **cmd[] = {ls, rev, nl, cat, NULL};
pipeline(cmd);
return (0);
}
@cluzze
Copy link

cluzze commented Dec 4, 2021

чел

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment