Created
September 14, 2021 10:14
-
-
Save Hermann-SW2/c696d282e5c0f2f8e94993e33673c162 to your computer and use it in GitHub Desktop.
C script for piping input onto n pipes for further processing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.raspberrypi.org/forums/viewtopic.php?f=33&t=319473&p=1913242#p1913242
Demo with 3 pipes:
Now demo with "pipe in pipe":