Sometimes you only want one instance of your program, i.e. one process running at any given time. I implemented this using two methods: by checking if the program is already running and by blocking on a file descriptor.
1. by checking if the program is already running
For this to work properly, you must ensure that the program name is unique. I used the following code in a MiniGUI program, but it always died. I have not debugged it.
/*
* usage example: ./check-process getty
*/
#include
#include
#include
int main (int argc, char* argv[]){
FILE* fp;
char buf[512];
char* p;
char* process;
int count = 0;
process = argv[1];
fp = popen ("ps -e", "r");
if (!fp){
fprintf (stderr, "popen failed\n");
exit (EXIT_FAILURE);
}
while ( (p = fgets (buf, sizeof(buf), fp)) != NULL ){
if (strstr (buf, process)){
count++;
fprintf (stderr, "%s is running\n", process);
}
}
if (count == 0)
fprintf (stderr, "no %s is found in current processes\n", process);
pclose (fp);
return 0;
}
2. by blocking on a file descriptor
fd_lock = open ("/tmp/.photoframe-proc-check", O_CREAT | O_RDWR | O_NONBLOCK);
if (fd_lock < 0){
perror ("open");
exit (EXIT_FAILURE);
}
//second instance of this program will fail flock and exit
if (flock (fd_lock, LOCK_EX | LOCK_NB) < 0){
perror ("flock");
exit (EXIT_FAILURE);
}
...
flock (fd_lock, LOCK_UN);
close (fd_lock);
Still a better way?
If a program is running and you use tftp to download a new version of the program to replace it, tftp will fail, saying that text file is busy. How does tftp tell the text file is busy? Is the method used by tftp a better way to do what we want here?
阅读(488) | 评论(0) | 转发(0) |