How to prevent a Linux program from running more t

2020-02-09 07:59发布

What is the best way to prevent a Linux program/daemon from being executed more than once at a given time?

7条回答
淡お忘
2楼-- · 2020-02-09 08:52

I believe my solution is the simplest:

(don't use it if racing condition is a possible scenario, but on any other case this is a simple and satisfying solution)

#include <sys/types.h>
#include <unistd.h>
#include <sstream>

void main()
{
    // get this process pid
    pid_t pid = getpid();

    // compose a bash command that:
    //    check if another process with the same name as yours
    //    but with different pid is running
    std::stringstream command;
    command << "ps -eo pid,comm | grep <process name> | grep -v " << pid;
    int isRuning = system(command.str().c_str());
    if (isRuning == 0) {
        cout << "Another process already running. exiting." << endl;
        return 1;
    }
    return 0;
}
查看更多
登录 后发表回答