How do I prevent multiple instances of same process to run at the same time?

    I would like to know the proper way to prevent the same instance of processes from running at the same time on UNIX. I would like to allow only one instance of process to run. If the same program were to execute again, it will check if there is same instance already running. If yes, then it will immediately terminate itself.

Best regards,
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

There's a few ways of doing it, but a very common way is to create a run file with the pid of the process.

A number of startup scripts for daemons use this method (varies slightly between Unix flavours).

For example:


prog=`basename $0`

if [ -f /var/run/$prog ]
     pid=`cat /var/run/$prog
     if ps -p $pid >/dev/null
           echo "$0 already running"

echo $$ >/var/run/$prog

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
nisaAuthor Commented:
    I accept the answer, thanks!. I have another question, I will give u extra 50 pts for that (if u have the info):

I know that we can use unix "system()" call ie system(<the script command here>) so that my C program can call it internally. Is there any alternative I can use ie by using unix call directly (without using the script) from the C program?

Best regards,
Your additional question depends entirely on what the script is doing.

There are a lot of commands that have C library equivalents, it all depends on what functions you are trying to do.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
System Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.