如何保证一个程序在单台服务器上只有唯一实例(linux)
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.
如何保证一个程序在单台服务器上只有唯一实例(linux)
如何保证一个程序在单台服务器上只有唯一实例呢,本着简单实用的思想写了一个实现函数:
以下是代码片段:
/* 判断当前进程是否已经运行 */
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;
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK