xref: /plan9-contrib/sys/src/cmd/lp/LOCK.c (revision 219b2ee8daee37f4aad58d63f21287faa8e4ffdc)
1 #include <u.h>
2 #include <libc.h>
3 
4 /* MAXHOSTNAMELEN is in sys/param.h */
5 #define MAXHOSTNAMELEN	64
6 
7 char lockstring[MAXHOSTNAMELEN+8];
8 
9 void
10 main(int argc, char *argv[]) {
11 	char *lockfile;
12 	int fd, ppid, ssize;
13 	struct Dir statbuf;
14 
15 	if (argc != 4) {
16 		fprint(2, "usage: LOCK lockfile hostname ppid\n");
17 		exits("lock failed on usage");
18 	}
19 	lockfile = argv[1];
20 	if ((fd=create(lockfile, ORDWR, CHEXCL|0666)) < 0) {
21 		exits("lock failed on create");
22 	}
23 	ppid = atoi(argv[3]);
24 	ssize = sprint(lockstring, "%s %s\n", argv[2], argv[3]);
25 	if (write(fd, lockstring, ssize) != ssize) {
26 		fprint(2, "LOCK:write(): %r\n");
27 		exits("lock failed on write to lockfile");
28 	}
29 
30 	switch(fork()) {
31 	default:
32 		exits("");
33 	case 0:
34 		break;
35 	case -1:
36 		fprint(2, "LOCK:fork(): %r\n");
37 		exits("lock failed on fork");
38 	}
39 
40 	for(;;) {
41 		if (dirfstat(fd, &statbuf) == -1 || statbuf.Length.length == 0)
42 			break;
43 		if (write(fd, "", 0) < 0)
44 			break;
45 		sleep(3000);
46 	}
47 
48 	close(fd);
49 	postnote(PNGROUP, ppid, "kill");
50 	exits("");
51 }
52