pipefile.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #define TEMP "/n/temp"
  12. void
  13. usage(void)
  14. {
  15. fprint(2, "usage: pipefile [-d] [-r command] [-w command] file\n");
  16. exits("usage");
  17. }
  18. void
  19. connect(char *cmd, int fd0, int fd1)
  20. {
  21. switch(rfork(RFPROC|RFFDG|RFREND|RFNOWAIT)){
  22. case -1:
  23. sysfatal("fork %s: %r", cmd);
  24. break;
  25. default:
  26. close(fd0);
  27. close(fd1);
  28. return;
  29. case 0:
  30. dup(fd0, 0);
  31. dup(fd1, 1);
  32. close(fd0);
  33. close(fd1);
  34. execl("/bin/rc", "rc", "-c", cmd, nil);
  35. sysfatal("exec %s: %r", cmd);
  36. break;
  37. }
  38. }
  39. void
  40. main(int argc, char *argv[])
  41. {
  42. char *file;
  43. char *rcmd, *wcmd;
  44. int fd0, fd1, ifd0, ifd1, dupflag;
  45. rfork(RFNOTEG);
  46. dupflag = 0;
  47. rcmd = wcmd = nil;
  48. ARGBEGIN{
  49. case 'd':
  50. dupflag = 1;
  51. break;
  52. case 'r':
  53. rcmd = EARGF(usage());
  54. break;
  55. case 'w':
  56. wcmd = EARGF(usage());
  57. break;
  58. default:
  59. usage();
  60. }ARGEND
  61. if(argc!=1 || (rcmd==nil && wcmd==nil))
  62. usage();
  63. if(rcmd == nil)
  64. rcmd = "/bin/cat";
  65. if(wcmd == nil)
  66. wcmd = "/bin/cat";
  67. file = argv[0];
  68. if(dupflag){
  69. ifd0 = open(file, ORDWR);
  70. if(ifd0 < 0)
  71. sysfatal("open %s: %r", file);
  72. ifd1 = dup(ifd0, -1);
  73. }else{
  74. ifd0 = open(file, OREAD);
  75. if(ifd0 < 0)
  76. sysfatal("open %s: %r", file);
  77. ifd1 = open(file, OWRITE);
  78. if(ifd1 < 0)
  79. sysfatal("open %s: %r", file);
  80. }
  81. if(bind("#|", TEMP, MREPL) < 0)
  82. sysfatal("bind pipe %s: %r", TEMP);
  83. if(bind(TEMP "/data", file, MREPL) < 0)
  84. sysfatal("bind %s %s: %r", TEMP "/data", file);
  85. fd0 = open(TEMP "/data1", OREAD);
  86. if(fd0 < 0)
  87. sysfatal("open %s: %r", TEMP "/data1");
  88. connect(wcmd, fd0, ifd1);
  89. fd1 = open(TEMP "/data1", OWRITE);
  90. if(fd1 < 0)
  91. sysfatal("open %s: %r", TEMP "/data1");
  92. connect(rcmd, ifd0, fd1);
  93. unmount(nil, TEMP);
  94. exits(nil);
  95. }