Skip to content

Instantly share code, notes, and snippets.

@iomonad
Last active June 15, 2024 17:15
Show Gist options
  • Save iomonad/a66f6e9cfb935dc12c0244c1e48db5c8 to your computer and use it in GitHub Desktop.
Save iomonad/a66f6e9cfb935dc12c0244c1e48db5c8 to your computer and use it in GitHub Desktop.
Multiple pipes in C (Not complete, only for concept purpose)
/*
** 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);
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);
}
@tapasm2027
Copy link

This is great example to understand multiple pipes , I was not clear with this concept but your code made me understand. Great work.

@profawxhawk
Copy link

When I try to run the command cat /bin/ls | wc -l the program displays nothing and the gdb de-bugger shows the following error:
Program received signal SIGINT, Interrupt.
0x00007fffff0e45f1 in __libc_wait (stat_loc=0x0) at ../sysdeps/unix/sysv/linux/wait.c:29
29 ../sysdeps/unix/sysv/linux/wait.c: No such file or directory.

How to resolve this issue?

@hansonkib
Copy link

great work, well illustrated,,thanks alot

@lubenard
Copy link

Great works but not complete work, it will fail to execute:
cat /dev/urandom | head -c 1000 | wc -c
because it wait for cat to finish, but head will finish first and stop cat

@JeffreyJoumjian
Copy link

Having an array of String arrays is a really elegant solution to splitting up your commands. I didn't figure you could do something like that in C. Thank you for reminding me that i should be using collection of collections more often in any language. :)

@WitoldG
Copy link

WitoldG commented Nov 25, 2019

I have a problem with your code when I execute a command like "time -p sleep 3 | echo toto". When I do it on the unix shell I get toto prited then 3 seconds after the time output. With your code the two outputs come after 3 seconds.

@PerSonnaYo
Copy link

It's a very very very great example to understand multiple pipes

@gybber-dev
Copy link

I think it has fd leak

@saad-qayyum
Copy link

this was great boy

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