标签归档:唯一程序实例

RSS feed of 唯一程序实例

最后更新于 .

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

/* 判断当前进程是否已经运行 */
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 ...