下面的一段程序可以防止程序被多次重复运行。
原理: 程序运行时会将程序pid保存在一个文件中,
当其它程序运行时,会读取这个pid,并且查看“/proc/[pid]”是否存在;
如果路径存在,说明已有程序在运行,推出, 如果不存在,运行程序
int main(int argc, char* argv[])
{
pid_t pid;
FILE *fp;
char pidBuf[10];
std::string pidTxtPath = curPath + "/pid.txt";
if((fp=fopen(pidTxtPath.c_str(), "r")) != NULL ){
fgets(pidBuf, 10, fp);
char pidPath[20];
sprintf(pidPath, "/proc/%s", pidBuf);
if(access(pidPath, F_OK) == 0)
{
printf("progress is running\n");
fclose(fp);
return -1;
}
fclose(fp);
}
pid = getpid();
if((fp=fopen(pidTxtPath.c_str(), "wb+")) == NULL)
{
printf("cannot open file\n");
exit(0);
}
fprintf(fp, "%d", pid);
fclose(fp);
/////////////// do program
}