• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 292
  • Last Modified:

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

Hello,
    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,
Nisa.
0
nisa
Asked:
nisa
  • 2
1 Solution
 
TintinCommented:
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:

#!/bin/sh

prog=`basename $0`

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

echo $$ >/var/run/$prog
           
0
 
nisaAuthor Commented:
Tintin,
    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,
Azmi.
0
 
TintinCommented:
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.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now