jehanne/sys/src/cmd/pipefile.c

106 lines
2.1 KiB
C

/*
* This file is part of the UCB release of Plan 9. It is subject to the license
* terms in the LICENSE file found in the top-level directory of this
* distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
* part of the UCB release of Plan 9, including this file, may be copied,
* modified, propagated, or distributed except according to the terms contained
* in the LICENSE file.
*/
#include <u.h>
#include <lib9.h>
#define TEMP "/n/temp"
void
usage(void)
{
fprint(2, "usage: pipefile [-d] [-r command] [-w command] file\n");
exits("usage");
}
void
connect(char *cmd, int fd0, int fd1)
{
switch(sys_rfork(RFPROC|RFFDG|RFREND|RFNOWAIT)){
case -1:
sysfatal("fork %s: %r", cmd);
break;
default:
sys_close(fd0);
sys_close(fd1);
return;
case 0:
dup(fd0, 0);
dup(fd1, 1);
sys_close(fd0);
sys_close(fd1);
execl("/cmd/rc", "rc", "-c", cmd, nil);
sysfatal("exec %s: %r", cmd);
break;
}
}
void
main(int argc, char *argv[])
{
char *file;
char *rcmd, *wcmd;
int fd0, fd1, ifd0, ifd1, dupflag;
sys_rfork(RFNOTEG);
dupflag = 0;
rcmd = wcmd = nil;
ARGBEGIN{
case 'd':
dupflag = 1;
break;
case 'r':
rcmd = EARGF(usage());
break;
case 'w':
wcmd = EARGF(usage());
break;
default:
usage();
}ARGEND
if(argc!=1 || (rcmd==nil && wcmd==nil))
usage();
if(rcmd == nil)
rcmd = "/cmd/cat";
if(wcmd == nil)
wcmd = "/cmd/cat";
file = argv[0];
if(dupflag){
ifd0 = sys_open(file, ORDWR);
if(ifd0 < 0)
sysfatal("open %s: %r", file);
ifd1 = dup(ifd0, -1);
}else{
ifd0 = sys_open(file, OREAD);
if(ifd0 < 0)
sysfatal("open %s: %r", file);
ifd1 = sys_open(file, OWRITE);
if(ifd1 < 0)
sysfatal("open %s: %r", file);
}
if(sys_bind("#|", TEMP, MREPL) < 0)
sysfatal("bind pipe %s: %r", TEMP);
if(sys_bind(TEMP "/data", file, MREPL) < 0)
sysfatal("bind %s %s: %r", TEMP "/data", file);
fd0 = sys_open(TEMP "/data1", OREAD);
if(fd0 < 0)
sysfatal("open %s: %r", TEMP "/data1");
connect(wcmd, fd0, ifd1);
fd1 = sys_open(TEMP "/data1", OWRITE);
if(fd1 < 0)
sysfatal("open %s: %r", TEMP "/data1");
connect(rcmd, ifd0, fd1);
sys_unmount(nil, TEMP);
exits(nil);
}