Skip to content

Commit

Permalink
Fix resource leak in create_pid_file().
Browse files Browse the repository at this point in the history
  • Loading branch information
Marco van Wieringen committed Feb 17, 2015
1 parent 036fd92 commit b0cb1ed
Showing 1 changed file with 30 additions and 17 deletions.
47 changes: 30 additions & 17 deletions src/lib/bsys.c
Expand Up @@ -502,7 +502,8 @@ static int del_pid_file_ok = FALSE;
void create_pid_file(char *dir, const char *progname, int port)
{
#if !defined(HAVE_WIN32)
int pidfd, len;
int pidfd = -1;
int len;
int oldpid;
char pidbuf[20];
POOLMEM *fname = get_pool_memory(PM_FNAME);
Expand All @@ -518,26 +519,38 @@ void create_pid_file(char *dir, const char *progname, int port)
berrno be;
Emsg2(M_ERROR_TERM, 0, _("Cannot open pid file. %s ERR=%s\n"), fname,
be.bstrerror());
} else {
/*
* Some OSes (IRIX) don't bother to clean out the old pid files after a crash, and
* since they use a deterministic algorithm for assigning PIDs, we can have
* pid conflicts with the old PID file after a reboot.
* The intent the following code is to check if the oldpid read from the pid
* file is the same as the currently executing process's pid,
* and if oldpid == getpid(), skip the attempt to
* kill(oldpid,0), since the attempt is guaranteed to succeed,
* but the success won't actually mean that there is an
* another BAREOS process already running.
* For more details see bug #797.
*/
if ((oldpid != (int)getpid()) && (kill(oldpid, 0) != -1 || errno != ESRCH)) {
Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
progname, oldpid, fname);
}
}
/* Some OSes (IRIX) don't bother to clean out the old pid files after a crash, and
* since they use a deterministic algorithm for assigning PIDs, we can have
* pid conflicts with the old PID file after a reboot.
* The intent the following code is to check if the oldpid read from the pid
* file is the same as the currently executing process's pid,
* and if oldpid == getpid(), skip the attempt to
* kill(oldpid,0), since the attempt is guaranteed to succeed,
* but the success won't actually mean that there is an
* another BAREOS process already running.
* For more details see bug #797.
*/
if ((oldpid != (int)getpid()) && (kill(oldpid, 0) != -1 || errno != ESRCH)) {
Emsg3(M_ERROR_TERM, 0, _("%s is already running. pid=%d\nCheck file %s\n"),
progname, oldpid, fname);

if (pidfd >= 0) {
close(pidfd);
}
/* He is not alive, so take over file ownership */

/*
* He is not alive, so take over file ownership
*/
unlink(fname); /* remove stale pid file */
}
/* Create new pid file */

/*
* Create new pid file
*/
if ((pidfd = open(fname, O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0640)) >= 0) {
len = sprintf(pidbuf, "%d\n", (int)getpid());
write(pidfd, pidbuf, len);
Expand Down

0 comments on commit b0cb1ed

Please sign in to comment.