remove stale pidfile if no such process found

This commit is contained in:
Martin Willi
2009-06-09 14:56:31 +02:00
parent fd0b7903e6
commit 4d8ddefb78
+44 -13
View File
@@ -611,6 +611,48 @@ private_daemon_t *daemon_create(void)
return this;
}
/**
* Check/create PID file, return TRUE if already running
*/
static bool check_pidfile()
{
struct stat stb;
FILE *file;
if (stat(PID_FILE, &stb) == 0)
{
file = fopen(PID_FILE, "r");
if (file)
{
char buf[64];
pid_t pid = 0;
memset(buf, 0, sizeof(buf));
if (fread(buf, 1, sizeof(buf), file))
{
pid = atoi(buf);
}
fclose(file);
if (pid && kill(pid, 0) == 0)
{ /* such a process is running */
return TRUE;
}
}
DBG1(DBG_DMN, "removing pidfile '"PID_FILE"', process not running");
unlink(PID_FILE);
}
/* create new pidfile */
file = fopen(PID_FILE, "w");
if (file)
{
fprintf(file, "%d\n", getpid());
ignore_result(fchown(fileno(file), charon->uid, charon->gid));
fclose(file);
}
return FALSE;
}
/**
* print command line usage and exit
*/
@@ -639,10 +681,7 @@ static void usage(const char *msg)
int main(int argc, char *argv[])
{
bool use_syslog = FALSE;
private_daemon_t *private_charon;
FILE *pid_file;
struct stat stb;
level_t levels[DBG_MAX];
int group;
@@ -723,21 +762,13 @@ int main(int argc, char *argv[])
destroy(private_charon);
exit(-1);
}
/* check/setup PID file */
if (stat(PID_FILE, &stb) == 0)
if (check_pidfile())
{
DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
destroy(private_charon);
exit(-1);
}
pid_file = fopen(PID_FILE, "w");
if (pid_file)
{
fprintf(pid_file, "%d\n", getpid());
ignore_result(fchown(fileno(pid_file), charon->uid, charon->gid));
fclose(pid_file);
}
/* drop the capabilities we won't need */
drop_capabilities(private_charon);