plan9port

fork of plan9port with libvec, libstr and libsdb
Log | Files | Refs | README | LICENSE

ipcopen.c (1606B)


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