Skip to content

Instantly share code, notes, and snippets.

@Hermann-SW2
Created September 14, 2021 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hermann-SW2/c696d282e5c0f2f8e94993e33673c162 to your computer and use it in GitHub Desktop.
Save Hermann-SW2/c696d282e5c0f2f8e94993e33673c162 to your computer and use it in GitHub Desktop.
C script for piping input onto n pipes for further processing
#!/bin/bash
exc=/tmp/pipn.c
if [ $0 -nt $exc ]; then sed -n "/^\/\*\*$/,\$p" $0 | gcc -x c - -o $exc; fi
cat | $exc "$@"
exit
/**
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define siz 1024
char cmds[siz];
char *cmd(char *s)
{
assert(10 < sprintf(cmds, "bash -c \"%s\"", s));
return cmds;
}
int main(int argc, char *argv[])
{
char buf[siz];
FILE **pip;
assert(argc>1);
int i, r, n = argc-1;
assert(pip = malloc(n*sizeof(FILE *)));
for(i=0; i<n; ++i) assert(pip[i] = popen(cmd(argv[i+1]), "w"));
r = fread(buf, 1, siz, stdin);
while (r > 0)
{
for(i=0; i<n; ++i) assert(r == fwrite(buf, 1, r, pip[i]));
r = fread(buf, 1, siz, stdin);
}
for(i=0; i<n; ++i) assert(-1 != pclose(pip[i]));
free(pip);
return 0;
}
@Hermann-SW2
Copy link
Author

https://www.raspberrypi.org/forums/viewtopic.php?f=33&t=319473&p=1913242#p1913242
Demo with 3 pipes:

$ echo -e "1\n2\n3\n4\n5\n6\n7\n8\n9\n10" | ./pipn.c "head -3" "wc" "tail -2"
1
2
3
     10      10      21
9
10
$ 

Now demo with "pipe in pipe":

$ echo -e "1\n2\n3\n4\n5\n6\n7\n8\n9\n10" | ./pipn.c "head -3 | wc" "tail -2"
      3       3       6
9
10
$ 

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