Skip to content

Instantly share code, notes, and snippets.

@doshiraki
Last active August 15, 2022 00:51
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 doshiraki/779dd679c9d05f3119250655bda70a7f to your computer and use it in GitHub Desktop.
Save doshiraki/779dd679c9d05f3119250655bda70a7f to your computer and use it in GitHub Desktop.
Cyclic pipe (you can do "your_pg | program | your_pg" )
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
void s2p(const char *path) {
char buf[2];
int fd = open(path, O_WRONLY);
while(fread(buf, 1, 1, stdin)) {
int cnt=1;
if (buf[0] == '\\') {
buf[1] = '\\';
cnt++;
}
write(fd, buf, cnt);
}
write(fd, "\\z", 2);
close(fd);
}
void p2s(const char *path) {
char buf[2];
int i = 0;
int fd = open(path, O_RDONLY);
while(read(fd, buf+i, 1)) {
switch(i) {
case 0:
if (buf[i] == '\\') {
i++;
continue;
}
break;
case 1:
if (buf[i] == 'z') {
goto close_fp;
} else if(buf[i] == '\\') {
i = 0;
} else {
fprintf(stderr, "%.2s is no escape char", buf);
goto close_fp;
}
break;
}
fwrite(buf, i+1, 1, stdout);
fflush(stdout);
i = 0;
}
close_fp:
close(fd);
}
int main(int argc, const char*argv[]) {
const char *cmdname = argv[0];
if (argc == 1) {
int pipefd[2];
char cmd[2000];
if(pipe(pipefd)){
perror("ng");
return -1;
}
int pid = getpid();
sprintf(cmd, "PIPEIN=\"%s s2p /proc/%d/fd/%d\" "
"PIPEOUT=\"%s p2s /proc/%d/fd/%d\" "
"bash", cmdname, pid, pipefd[0]
, cmdname, pid, pipefd[1]);
fflush(stdout);
system(cmd);
close(pipefd[0]);
close(pipefd[1]);
} else if (argc == 3) {
const char *subcmd = argv[1];
const char *fname = argv[2];
if (strcmp(subcmd, "s2p")) {
s2p(fname);
} else if (strcmp(subcmd, "p2s")) {
p2s(fname);
}
} else {
fprintf(stderr, "%s", "パラメータが不正です");
}
return 0;
}
@doshiraki
Copy link
Author

インタプリタをサイクリックなパイプで利用することができる。
$PIPEIN | bash | tee /dev/stderr | python ./test.py | tee /dev/stderr | $PIPEOUT

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