Find the answer to your Linux question:
Results 1 to 2 of 2
Hi all, I'm writing a C program that should not allow multiple instances of itself to run o the system. What is the approach on Linux? On Windows this can ...
  1. #1
    Just Joined!
    Join Date
    Sep 2007
    Posts
    6

    Allow a single instance of a process to run (in C)

    Hi all,

    I'm writing a C program that should not allow multiple instances of itself to run o the system. What is the approach on Linux?
    On Windows this can be done using named mutexs.

    I tried using a semaphore (System V) and it works, but there is a problem. If the process crashes, than the semaphore still remains open. And I wold never be able to start the process again, until reboot.
    Since this will be a server application, crashes would happen in real world, so I need another solution.

    So, what is the common practice for this functionality?

  2. #2
    Just Joined! raj.aprilfool's Avatar
    Join Date
    Dec 2006
    Location
    Mumbai, India
    Posts
    35
    in linux, for each running process there is one directory created under /proc dir, that directory has process id as it directory name.......
    u need to create pid file which stores process id of ur current process......
    the default location for pid file is /var/run/

    e.g......
    #define PID_FILE "/var/run/simplserver.pid"

    pid=getpid();
    snprintf(buf,sizeof(buf),"%d",pid);
    if((pidfd=open(PID_FILE,O_WRONLY|O_CREAT))<0)
    {
    exit(EXIT_FAILURE);
    }
    if((byteread=write(pidfd,buf,strlen(buf)))<0)
    {
    exit(EXIT_FAILURE);
    }


    also, before u start off u need to check if ur pid file already exists or not.....
    if it exists... read the pid from the file... and check if the directory of that name already
    exists or not..... if it exists.... to be on the safer side try to read status file inside that directory..... and check the application name matches ur binary name.......

    this might help...................
    do correct me if i'm wrong...........

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...