src/lib/daemon.c in trema-0.4.4 vs src/lib/daemon.c in trema-0.4.5
- old
+ new
@@ -227,20 +227,32 @@
char path[ PATH_MAX ];
snprintf( path, PATH_MAX, "%s/%s.pid", directory, name );
path[ PATH_MAX - 1 ] = '\0';
+ int fd = open( path, O_RDWR, 0 );
+ if ( fd < 0 ) {
+ debug( "Failed to open %s ( %s [%d] ).", path, strerror( errno ), errno );
+ return;
+ }
+ if ( lockf( fd, F_TLOCK, 0 ) == -1 ) {
+ warn( "PID file is locked by another process ( %s ).", path );
+ close( fd );
+ return;
+ }
+
int ret = unlink( path );
if ( ret < 0 ) {
if ( errno == ENOENT ) {
warn( "PID file %s does not exist", path );
}
else {
die( "Could not remove a PID file: %s", path );
}
}
debug( "Unlink pid file ( file = %s, pid = %d )", path, getpid() );
+ close( fd );
}
pid_t
read_pid( const char *directory, const char *name ) {
@@ -400,11 +412,11 @@
assert( locked_fd > -1 );
int old_locked_fd = locked_fd;
locked_fd = -1;
write_pid( directory, new );
- close( old_locked_fd );
unlink_pid( directory, old );
+ close( old_locked_fd );
debug( "Rename pid file ( old name = %s, new name = %s, pid = %d )", old, new, getpid() );
}