10

如何保证一个程序在单台服务器上只有唯一实例(linux)

 3 years ago
source link: https://blogread.cn/it/article/786?f=hot1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如何保证一个程序在单台服务器上只有唯一实例(linux)

浏览:2815次  出处信息

    如何保证一个程序在单台服务器上只有唯一实例呢,本着简单实用的思想写了一个实现函数:



以下是代码片段:
/* 判断当前进程是否已经运行 */
static bool is_running(const char* prg)
{
    const char* pid_file = “.tmp_pid”;
    const char* p = strrchr(prg, ‘/’);
    if (p)
    {
        p++;
    }
    else
    {
        p = prg;
    }
    char cmd[128] = {0};
    sprintf(cmd, “pgrep %s >%s”, p, pid_file);
    system(cmd);
    std::string s;
    FILE* fp = fopen(pid_file, “r”);
    if (fp == NULL)
    {
        fprintf(stderr, “ERROR: can not open pid file: %s!\n”, pid_file);
        return false;
    }
    int pid;
    while (read_line(fp, s))
    {
        pid = atoi(s.c_str());
        if ((pid_t)pid != getpid())
        {
            break;
        }
        else
        {
            pid = 0;
        }
    }
    fclose(fp);
    sprintf(cmd, “rm -f %s”, pid_file);
    system(cmd);
    return pid>0;
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK