Skip to content

Instantly share code, notes, and snippets.

@Hermann-SW2
Created Sep 14, 2021
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@Hermann-SW2 Hermann-SW2 commented Sep 14, 2021

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