From 1bb78bf47650bcaccb359ae774554bcbc10934ab Mon Sep 17 00:00:00 2001 From: erdgeist <> Date: Tue, 12 Mar 2013 19:04:26 +0000 Subject: Use the pidfile library to write the pidfile --- jaildaemon.c | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/jaildaemon.c b/jaildaemon.c index 4b6c923..918f01b 100644 --- a/jaildaemon.c +++ b/jaildaemon.c @@ -17,12 +17,15 @@ #include #include #include +#include #define IPC_PACKETSIZE 4096 #define MAGIC_EXIT_CODE 42 enum { IAM_DAEMON, IAM_CLIENT, IAM_FORKSLAVE }; static int g_uds; static int g_whoami = IAM_CLIENT; +static struct + pidfh * g_pidfilehandle; static int g_fork_slave_fd; static char g_ipc_packet[IPC_PACKETSIZE]; static int * const g_ipc_packet_int = (int*)g_ipc_packet; @@ -144,6 +147,8 @@ static int fork_fork_slave( ) { /* I am child, close master's socket fd */ close( sockets[0] ); g_whoami = IAM_FORKSLAVE; + pidfile_close( g_pidfilehandle ); + g_pidfilehandle = NULL; fork_slave( sockets[1] ); /* Never returns */ exit(0); default: @@ -285,6 +290,8 @@ static void kill_all_probes( void ) { g_probes_size = 0; free( g_probes ); g_probes = 0; + + pidfile_remove( g_pidfilehandle ); } static int add_task_to_kqueue( int kq, daemon_task * t_in ) { @@ -394,23 +401,27 @@ int main( int argc, char **argv ) { } } - /* Start a fork slave while there is no file descriptors or initialized - memory yet. Communicate with this slave via socketpair */ + /* Daemonize and start a fork slave while there is no file descriptors or + initialized memory yet. Communicate with this slave via socketpair */ if( o_daemonize ) { - if( daemon(1,0) == -1 ) - exerr( "daemonzing" ); - g_fork_slave_fd = fork_fork_slave( ); + g_pidfilehandle = pidfile_open(o_pidfile, 0600, NULL ); + + if (!g_pidfilehandle) { + if (errno == EEXIST) + exerr( "jaildaemon already running." ); + /* If we cannot create pidfile from other reasons, only warn. */ + warn( "Cannot open or create pidfile" ); + } - /* When we're supposed to write a pidfile, just do it */ - if( o_pidfile ) { - FILE *fp = fopen( o_pidfile, "w"); - if (!fp) - exerr("opening pid file"); - fprintf(fp, "%d\n", (int)getpid()); - fclose(fp); + if( daemon(1,0) == -1 ) { + pidfile_remove(g_pidfilehandle); + exerr( "daemonzing" ); } + pidfile_write(g_pidfilehandle); + + g_fork_slave_fd = fork_fork_slave( ); - openlog( "jaildaemon", 0, LOG_DAEMON ); + openlog( "jaildaemon", 0, LOG_DAEMON ); setlogmask(LOG_UPTO(LOG_INFO)); g_whoami = IAM_DAEMON; -- cgit v1.2.3