tags:

views:

37

answers:

2

Hello to all, I have create a simple application which using C++ and produce a executable file.

I would like to ensure the process cannot be start twice. How to enforce a process/service is start once only ?

Thanks.

+1  A: 

Write a temporary file and use it as a lock.

Edit: To answer the comment: If you are on a Unix system, write a file /tmp/my_application_lock_file. If it already exists, stop your program with an appropriate message. On exit of the creator of the file, delete it.

#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <iostream>
#include <fstream>

int main (void)
{
    struct stat file_info;
    // test for lock file
    if (stat("/tmp/my_application_lock", &file_info) == 0) {
        std::cout << "My application is already running, will abort now..." << std::endl;
        return -1;
    } else {
        // create lock file
        std::ofstream out;
        out.open("/tmp/my_application_lock");
        if (!out) {
            std::cout << "Could not create lock file!" << std::endl;
            return -1;
        }
        out << "locked" << std::endl;
        out.close();
        // do some work
        std::string s;
        std::cin >> s;
        // remove lock file
        errno = 0;
        if (unlink("/tmp/my_application_lock"))
            std::cout << "Error: " << strerror(errno) << std::endl;
    }
    return 0;
}
swegi
Can you please elaborate more on this ?
peterwkc
Thanks. Can you provide an example ?
peterwkc
Thanks for your example.
peterwkc
+2  A: 

What operating system? On Windows, the typical way to do this is to create a named Mutex, because the OS will give you an ERROR_ALREADY_EXISTS if some other process already created a mutex with that name, and the OS will ensure that the mutex is released when the process ends (even if it crashes or is killed).

nikie
How about a portable approach using some library ? or on Linux operating system.
peterwkc
Can you provide an example ? Thanks
peterwkc