I’ve been using a modified class I found to check if another instance of the same process is already running, the problem is that the method of checking for the process adds another instance of the same process.
When my application starts, a new process ID is created and is visible with:
ps -A | grep "AppName"
With this I get a since entry returned, I then check for another instance of the application using:
QString strCMD = "ps -A | grep "" + mcstrAppName + """; QProcess objProc; objProc.start("bash", QStringList() << "-c" << strCMD); if ( objProc.waitForStarted() != true || objProc.waitForFinished() != true ) { mcpobjApp->exit(cleanExit(-1, "Unable to determine if another instance is running!")); return; }
As soon as the ‘start’ method is called another instance of the same application appears in the process table, again, verified with:
ps -A | grep "AppName"
Two entries now appear each with a different PID. I’ve also tried:
QString strOptions = "-A | grep "" + mcstrAppName + """; QProcess objProc; objProc.start("ps", QStringList() << strOptions);
The result is the same, two entries in process table.
Is there a way to check the process table for another instance without adding an additional instance?
Advertisement
Answer
I recommend using a pid file. It’s the standard procedure for daemons on linux.
int createPidFile(const char *pidFile, int flags) { int fd; char buf[BUF_SIZE]; fd = open(pidFile, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if (fd == -1) errExit("Could not open PID file %s", pidFile); if (flags & CPF_CLOEXEC) { /* Set the close-on-exec file descriptor flag */ flags = fcntl(fd, F_GETFD); /* Fetch flags */ if (flags == -1) errExit("Could not get flags for PID file %s", pidFile); flags |= FD_CLOEXEC; /* Turn on FD_CLOEXEC */ if (fcntl(fd, F_SETFD, flags) == -1) /* Update flags */ errExit("Could not set flags for PID file %s", pidFile); } return fd; }
Source The Linux Programming Interface
This creates a file and locks it so no other process can open it. It marks it as close on exit so the file will close when the process exits through normal or abnormal termination. If an instance of your program is already running, this function will fail and you can just exit.
EDIT: The pid file should be in the temporary partition. the specific location varies depending on your distribution, just look on your system where other daemons create their pid files.