]> rtime.felk.cvut.cz Git - frescor/forb.git/blob - src/daemon.c
forb: Split forb_port_destroy() to stop and destroy phases
[frescor/forb.git] / src / daemon.c
1 #include <forb.h>
2 #include <stdio.h>
3 #include <unistd.h>
4
5 /* Helper functions to "daemonize" forb servers. To make debugging
6  * easier, we do not detach from terminal. The idea behind daemonizing
7  * is to exit the parent when the server is ready to receive requests,
8  * so that is is not necessary to put delays between invocation of
9  * different servers. */
10
11 static int daemon_pipe[2] = { 0, 0 };
12
13 void forb_daemon_prepare(const char *pid)
14 {
15         pid_t child;
16         int ret;
17         FILE *f;
18         char tmp;
19
20         ret = pipe(daemon_pipe);
21         if (ret) {
22                 perror("pipe");
23                 exit(1);
24         }
25         child = fork();
26         if (child == -1) {
27                 perror("fork");
28                 exit(1);
29         }
30         if (child > 0) {        /* In parent */
31                 close(daemon_pipe[1]);
32                 ret = read(daemon_pipe[0], &tmp, 1);
33                 if (pid) {
34                         f = fopen(pid, "w");
35                         if (f) {
36                                 fprintf(f, "%d\n", child);
37                                 fclose(f);
38                         }
39                 }
40                 exit(ret > 0 ? 0 : 1);
41         } else {                /* In chind */
42                 close(daemon_pipe[0]);
43         }
44 }
45
46 /** 
47  * Signal the parent that the daemon is ready so that the parent can
48  * exit().
49  */
50 void forb_daemon_ready()
51 {
52         if (daemon_pipe[1])
53                 write(daemon_pipe[1], "", 1);
54 }
55