Fix tsak process locking

Fork off tsak daemon automatically
pull/1/head
Timothy Pearson 13 years ago
parent bb1850b7c3
commit c6cb95adbb

@ -144,39 +144,62 @@ void tearDownPipe()
} }
} }
void setupPipe() bool setFileLock(int fd, bool close_on_failure)
{ {
/* Create the FIFOs if they do not exist */ struct flock fl;
umask(0);
mkdir(FIFO_DIR,0644);
mknod(FIFO_FILE_OUT, S_IFIFO|0600, 0); fl.l_type = F_WRLCK;
chmod(FIFO_FILE_OUT, 0600); fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 1;
mPipe_fd_out = open(FIFO_FILE_OUT, O_WRONLY | O_NONBLOCK); // Set the exclusive file lock
if (mPipe_fd_out > -1) { if (fcntl(mPipe_fd_out, F_SETLK, &fl) == -1) {
mPipeOpen_out = true; close(mPipe_fd_out);
return false;
} }
return true;
} }
bool checkLocks() bool checkFileLock()
{ {
int fdlock;
struct flock fl; struct flock fl;
fl.l_type = F_WRLCK; fl.l_type = F_WRLCK; /* Test for any lock on any part of file. */
fl.l_whence = SEEK_SET; fl.l_start = 0;
fl.l_start = 0; fl.l_whence = SEEK_SET;
fl.l_len = 1; fl.l_len = 0;
int fd = open(FIFO_FILE_OUT, O_RDWR | O_NONBLOCK);
fcntl(fd, F_GETLK, &fl); /* Overwrites lock structure with preventors. */
fdlock = open(FIFO_FILE_OUT, O_RDWR | O_NONBLOCK); if (fd > -1) {
if (fdlock != -1) { if (fl.l_type == F_WRLCK) {
if(fcntl(fdlock, F_SETLK, &fl) == -1) { return false;
return 0;
} }
return true;
} }
return 1; return true;
}
bool setupPipe()
{
/* Create the FIFOs if they do not exist */
umask(0);
mkdir(FIFO_DIR,0644);
mknod(FIFO_FILE_OUT, S_IFIFO|0600, 0);
chmod(FIFO_FILE_OUT, 0600);
mPipe_fd_out = open(FIFO_FILE_OUT, O_RDWR | O_NONBLOCK);
if (mPipe_fd_out > -1) {
mPipeOpen_out = true;
}
// Set the exclusive file lock
return setFileLock(mPipe_fd_out, true);
} }
class PipeHandler class PipeHandler
@ -214,13 +237,18 @@ int main (int argc, char *argv[])
} }
} }
if (!checkLocks()) { // Check for existing file locks
if (!checkFileLock()) {
fprintf(stderr, "Another instance of this program is already running\n"); fprintf(stderr, "Another instance of this program is already running\n");
return 8; return 8;
} }
// Create the output pipe // Create the output pipe
PipeHandler controlpipe; PipeHandler controlpipe;
if (!setupPipe()) {
fprintf(stderr, "Another instance of this program is already running\n");
return 8;
}
while (1) { while (1) {
if ((getuid ()) != 0) { if ((getuid ()) != 0) {
@ -283,6 +311,14 @@ int main (int argc, char *argv[])
fprintf(stderr,"Device created.\n"); fprintf(stderr,"Device created.\n");
if (established == false) { if (established == false) {
tearDownPipe();
int i=fork();
if (i<0) return 9; // fork failed
if (i>0) {
// close parent process
close(mPipe_fd_out);
return 0;
}
setupPipe(); setupPipe();
} }

Loading…
Cancel
Save