ipcopen.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <u.h>
  2. #include <libc.h>
  3. int ppid;
  4. /*
  5. * predefined
  6. */
  7. void pass(int from, int to);
  8. /*
  9. * Connect to given datakit port
  10. */
  11. main(int argc, char *argv[])
  12. {
  13. int fd0, fd1;
  14. int cpid;
  15. char c;
  16. char *cp, *devdir, *buf;
  17. if (argc != 4) {
  18. fprint(2, "usage: %s destination network service\n", argv[0]);
  19. exits("incorrect number of arguments");
  20. }
  21. if(!(cp = malloc((long)(strlen(argv[1])+strlen(argv[2])+strlen(argv[3])+8)))) {
  22. perror("malloc");
  23. exits("malloc failed");
  24. }
  25. sprint(cp, "%s!%s!%s", argv[2], argv[1], argv[3]);
  26. if (dial(cp, &devdir, 0) < 0) {
  27. fprint(2, "dialing %s\n", cp);
  28. perror("dial");
  29. exits("can't dial");
  30. }
  31. /*
  32. * Initialize the input fd, and copy bytes.
  33. */
  34. if(!(buf = malloc((long)(strlen(devdir)+6)))) {
  35. perror("malloc");
  36. exits("malloc failed");
  37. }
  38. sprint(buf, "%s/data", devdir);
  39. fd0=open(buf, OREAD);
  40. fd1=open(buf, OWRITE);
  41. if(fd0<0 || fd1<0) {
  42. print("can't open", buf);
  43. exits("can't open port");
  44. }
  45. ppid = getpid();
  46. switch(cpid = fork()){
  47. case -1:
  48. perror("fork failed");
  49. exits("fork failed");
  50. case 0:
  51. close(0);
  52. close(fd1);
  53. pass(fd0, 1); /* from remote */
  54. hangup(fd0);
  55. close(1);
  56. close(fd0);
  57. exits("");
  58. default:
  59. close(1);
  60. close(fd0);
  61. pass(0, fd1); /* to remote */
  62. hangup(fd1);
  63. close(0);
  64. close(fd1);
  65. exits("");
  66. }
  67. }
  68. void
  69. pass(int from, int to)
  70. {
  71. char buf[1024];
  72. int ppid, cpid;
  73. int n, tot = 0;
  74. while ((n=read(from, buf, sizeof(buf))) > 0) {
  75. if (n==1 && tot==0 && *buf=='\0')
  76. break;
  77. tot += n;
  78. if (write(to, buf, n)!=n) {
  79. perror("pass write error");
  80. exits("pass write error");
  81. }
  82. }
  83. }