环境:ubuntu, buildroot
功能:禁止进程多开
char pidBuf[10];
const char *wiwtool_spid = "/tmp/spid.dat";
if ((fp = fopen(wiwtool_spid, "r")) != NULL) {
fgets(pidBuf, 10, fp);
char pidPath[20];
sprintf(pidPath, "/proc/%s", pidBuf);
if (access(pidPath, F_OK) == 0) {
//wdbg_log("the process is running\n");
fclose(fp);
return 0;
}
fclose(fp);
}
pid_t pid = getpid();
if ((fp = fopen(wiwtool_spid, "wb+")) == NULL) {
//wdbg_log("cannot run...\n");
return 0;
}
fprintf(fp, "%d", pid);
fclose(fp);
参考:https://blog.youkuaiyun.com/fishrain/article/details/8241624
该博客介绍了在Ubuntu系统中,通过读写临时文件`/tmp/spid.dat`来检查并确保进程只有一个实例运行的方法。代码示例中,首先尝试读取`spid.dat`文件,如果文件内容对应的有效进程存在,则返回,否则创建新进程并写入当前PID到文件,以防止进程多开。
1210

被折叠的 条评论
为什么被折叠?



