LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How can i make sure there is only one my programme is running at the same time (https://www.linuxquestions.org/questions/programming-9/how-can-i-make-sure-there-is-only-one-my-programme-is-running-at-the-same-time-650014/)

hcj9999 06-17-2008 09:12 PM

How can i make sure there is only one my programme is running at the same time
 
I have writed a programe a.out,I can run it many times, so there are lots of running a.out in the systerm.I want to make sure there is only one a.out is running at the same time?

jdelongpre 06-17-2008 09:53 PM

One way to make the issue less confusing is to call your program something other than a.out. To do that, use the -o tag. for example
gcc -o hello hello.c

You could also run a script to see if your program is already running. For instance,
the command ps shows all processes, or ps -e shows all processes for all users.
Therefor, ps -e | grep hello would return any process containing hello and
ps -e | grep -q hello would just set a condition that you could test before
you start an instance of hello.

devnux 06-18-2008 01:41 AM

A better way to do it is to store a file somewhere (in /tmp for example) that indicates a running instance of your executable. Once your program has finished its job it must delete it.
So the pseudo-code would be :
Code:

main(){
 if there is no file called /tmp/myexec.run {
    create a file called /tmp/myexec.run
    ...
    ...
    delete the file.
 }
 else; // An instance is running. Nothing to do (or maybe print a message)
}

Usually programs running as root store this file in /var/run/myprocess.pid. You can take a look at some of them.

Hope it helps.

Hko 06-18-2008 02:27 AM

The tmp file method will work. But for a more solid method, see this thread.

jdelongpre 06-18-2008 01:14 PM

I agree with Hko, given that you have the source for your program. Since you already said that, I DID know. Still, name your program something other than a.out, too.

hcj9999 06-18-2008 09:03 PM

thank you very much! a.out is just a exmaple.

osor 06-19-2008 05:49 PM

In addition to the file-locking proposed by Hko, there are plenty of IPC mechanisms available (e.g., UNIX domain sockets or semaphores).


All times are GMT -5. The time now is 08:24 PM.