| iMatix home page | << | < | > | >> |
![]() Version 1.91 |
#include "sflproc.h" int process_server ( const char *workdir, /* Where server runs, or NULL/"" */ const char *lockfile) /* For exclusive execution */
Converts the process from an interactive foreground process into a background process. The precise effect of this depends on the system. On UNIX, does this:
{ #if (defined (__UNIX__)) int fork_result, file_handle; char pid_buffer [10]; struct flock lock_file; /* flock() argument block */ /* We recreate our process as a child of init. The process continues */ /* to exit in the background. UNIX calls wait() for all children of */ /* the init process, so the server will exit cleanly. */ fork_result = fork (); if (fork_result < 0) /* < 0 is an error */ return (-1); /* Could not fork */ else if (fork_result > 0) /* > 0 is the parent process */ exit (EXIT_SUCCESS); /* End parent process */ /* We close all open file descriptors that may have been inherited */ /* from the parent process. This is to reduce the resources we use. */ for (file_handle = FILEHANDLE_MAX - 1; file_handle >= 0; file_handle--) close (file_handle); /* Ignore errors */ /* We move to a safe and known directory, which is supplied as an */ /* argument to this function (or not, if workdir is NULL or empty). */ if (workdir && strused (workdir)) chdir (workdir); /* We set the umask so that new files are given mode 750 octal */ umask (027); /* Complement of 0750 */ /* We set standard input and output to the null device so that any */ /* functions that assume that these files are open can still work. */ file_handle = open ("/dev/null", O_RDWR); /* stdin = handle 0 */ dup (file_handle); /* stdout = handle 1 */ dup (file_handle); /* stderr = handle 2 */ /* We enforce a lock on the lockfile, if specified, so that only one */ /* copy of the server can run at once. We return -1 if the lock fails. */ /* This locking code might be better isolated into a separate package, */ /* since it is not very portable between unices. */ if (lockfile && strused (lockfile)) { file_handle = open (lockfile, O_RDWR | O_CREAT, 0640); if (file_handle < 0) return (-1); /* We could not open lock file */ else { lock_file.l_type = F_WRLCK; if (fcntl (file_handle, F_SETLK, &lock_file)) return (-1); /* We could not obtain a lock */ } /* We record the server's process id in the lock file */ sprintf (pid_buffer, "%6d\n", getpid ()); write (file_handle, pid_buffer, strlen (pid_buffer)); } /* We ignore any hangup signal from the controlling TTY */ signal (SIGHUP, SIG_IGN); return (0); /* Initialisation completed ok */ #else return (0); /* Nothing to do on this system */ #endif }
| << | < | > | >> |
![]() |