+static int
+InitDaemon(void)
+{
+ pid_t pid;
+ FILE *pidfile;
+
+ pidfile = fopen(PIDFILE, "w");
+ if (pidfile == NULL) {
+ fprintf(stderr, "%s creation failed\n", PIDFILE);
+ return(-1);
+ }
+
+ if ((pid = fork()) < 0) {
+ fclose(pidfile);
+ return(-1);
+ }
+ else if (pid != 0) {
+ /* i'm the parent, writing down the child pid */
+ fprintf(pidfile, "%u\n", pid);
+ fclose(pidfile);
+ exit(0);
+ }
+
+ /* close the pid file */
+ fclose(pidfile);
+
+ /* routines for any daemon process
+ 1. create a new session
+ 2. change directory to the root
+ 3. change the file creation permission
+ */
+ setsid();
+ chdir("/");
+ umask(0);
+
+ return(0);
+}
+/*-----------------------------------------------------------------*/
+static int
+OpenLogFile(void)
+{
+ static const char* logfile = "/var/log/codemux.log";
+ int logfd;
+
+ logfd = open(logfile, O_WRONLY | O_APPEND | O_CREAT, 0600);
+ if (logfd < 0) {
+ fprintf(stderr, "cannot open the logfile err=%s\n",
+ strerror(errno));
+ exit(-1);
+ }
+
+ /* duplicate logfile to stderr */
+ if (dup2(logfd, STDERR_FILENO) != STDERR_FILENO) {
+ fprintf(stderr, "cannot open the logfile err=%s\n",
+ strerror(errno));
+ exit(-1);
+ }
+
+ /* set the close-on-exec flag */
+ if (fcntl(STDERR_FILENO, F_SETFD, 1) != 0) {
+ fprintf(stderr, "fcntl to set the close-on-exec flag failed err=%s\n",
+ strerror(errno));
+ exit(-1);
+ }
+
+ return logfd;
+}
+/*-----------------------------------------------------------------*/