unix/fiss-minit

pidfilehack.c in master
Repositories | Summary | Log | Files | README | COPYING

pidfilehack.c (1446B) download


 1#include <errno.h>
 2#include <fcntl.h>
 3#include <stdio.h>
 4#include <stdlib.h>
 5#include <unistd.h>
 6
 7/* purpose: argv[1] is the full path to a PID file,
 8 *          argv+2 is the daemon to run.
 9 * the daemon is expected to fork in the background and write its PID in
10 * the pid file.
11 */
12
13extern char** environ;
14
15int main(int argc, char* argv[]) {
16	int count = 0;
17	if (argc < 3) {
18		write(1, "usage: pidfilehack service /var/run/daemon.pid /usr/sbin/daemon args...\n", 72);
19		return 0;
20	}
21	if (unlink(argv[2])) {
22		if (errno != ENOENT) {
23			perror("could not remove pid file");
24			return 1;
25		}
26	}
27	switch (fork()) {
28		case -1:
29			perror("could not fork");
30			return 2;
31		case 0: /* child */
32			execve(argv[3], argv + 3, environ);
33			perror("execvp failed");
34			return 3;
35	}
36	do {
37		int fd = open(argv[2], O_RDONLY);
38		if (fd >= 0) {
39			static char buf[100] = "-P";
40			int         len      = read(fd, buf + 2, 98);
41			close(fd);
42			if (len > 0) {
43				char* _argv[] = { "msvc", 0, 0, 0 };
44				if (buf[len + 1] == '\n')
45					buf[len + 1] = 0;
46				else
47					buf[len + 2] = 0;
48				_argv[1] = buf;
49				_argv[2] = argv[1];
50				/*	printf("execvp %s %s %s\n",_argv[0],_argv[1],_argv[2]); */
51				execvp(_argv[0], _argv);
52				perror("execvp failed");
53				return 0;
54			} /* else
55		  printf("file there but open returned %d\n",fd); */
56		}     /* else
57		      printf("%s not there yet\n",argv[2]); */
58		sleep(1);
59		if (++count >= 30)
60			exit(0);
61	} while (1);
62}