Play and learn 300 000+ tabs online

Tuesday, June 22, 2010

How to write program to run Only one executable in Unix

<code><var style="font-style: normal; color: rgb(0, 0, 176);">The following program to make sure that we are running only one instance of a program in Unix :-) 

The concept is based on the named key Creation when creating any IPC mechanism.


int</var> main()
{
sem_t *mysem;
mysem = sem_open(<kbd style="font-style: normal; color: rgb(96, 0, 48);">"MyUniqueName"</kbd>, O_CREAT|O_EXCL);
<var style="font-style: normal; color: rgb(0, 0, 176);">if</var> ( mysem == NULL )
{
fprintf(stderr, <kbd style="font-style: normal; color: rgb(96, 0, 48);">"I am already running!\n"</kbd>);
exit(1);
}

<cite style="font-style: normal; color: rgb(0, 112, 0);">/* the app code here*/</cite>

<cite style="font-style: normal; color: rgb(0, 112, 0);">/* end of the app */</cite>

sem_unlink(<kbd style="font-style: normal; color: rgb(96, 0, 48);">"MyUniqueName"</kbd>);
sem_close(mysem);
}</code>

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.