Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Avoiding Duplicate Copy

Status
Not open for further replies.

logic4fun

Programmer
Apr 24, 2003
85
US
I have a C program with embedded SQL in it. All it does is it kicks off from a shellScript with a particular sleep. I wanted to add a logic to the program where it doesnot allow a duplicate copy of my C program to run. to be specific on a box only one copy should run. and if someone tries to run another It should freak out with an error. Any Ideas In C coz i wanted to add that logic to the C program.

thanks in advance
logic4fun
 
One simple way is to create a lock file
Code:
FILE *fp = fopen( "/tmp/lock", "w" );
if ( fp != NULL ) {
  // do your thing
  // ...
  fclose( fp );  // release the lock
} else {
  printf("someone else running\n");
}

--
 
lock file technique is good. but we dont want to rely on file handles and files as this is a critical application and in somecases the file system may put us..in trouble.

thanks
logic4fun
 
Ok, so which OS are you running on then?
Perhaps the same idea using some other kind of OS resource (temporary files, shared memory, semaphores) will work better for you.



--
 
If you don't want to use a lock/pid file (which would be my first choice), I would suggest using semaphores. This is the type of thing that semaphores do well: controlling access to resources (in this case your program). Of course, semaphores are more complex than using a lock file and will require more code.

If you want some code I could post some.

Good Luck.
 
I dont have any experience with semaphores. can u please get me a start with an example

thanks
logic4fun
 
I don't have the code right here. Take a look at:


You will probably need to define the union semun before its use (see man semctl):

union semun {
int val;
struct semid_ds *buf;
unsigned short int *array;
struct seminfo *__buf;
};

Also, pay special attention to the ftok() function to insure that you are generating a unique key.

Hope this helps.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top