Here’s a simple “hello world” C program that takes 10 seconds to complete:
#include<stdio.h>
main()
{
printf("hello World 1 \n");
fflush(stdout);
sleep(10);
printf("hello World 2 \n");
fflush(stdout);
}
How can I modify it so at most only one instance of this executable can run at any moment in time? I’m using Linux.
For example, assume the server crashes if more than one instance is run simultaneously, and we’re trying to prevent this. I’d like to see one or more example(s) of different ways so I can run and verify on my system.
Also, is there a simple way to queue them so if I run the C executable twice in a row, the second one runs just after the first one completes?
Typically you usually acquire a file lock, create a run time file of a given file name with the process PID as the contents at initialization time (In a UNIX system usually in
/var/run/). Delete the file on exit.If the file already exists during startup, then another instance is already running.