linux保证程序单实例运行

Posted mingzhang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linux保证程序单实例运行相关的知识,希望对你有一定的参考价值。

static int proc_detect(const char *procname)
{
char filename[100] = {0};
sprintf(filename, "%s/%s.pid", LOG_DIR, procname);

int fd = open(filename, O_RDWR | O_CREAT, (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
if (fd < 0) {
printf("open file "%s" failed!!! ", filename);
return 1;
}

struct flock fl;
fl.l_type = F_WRLCK;
fl.l_start = 0;
fl.l_whence = SEEK_SET;
fl.l_len = 0;

int ret = fcntl(fd, F_SETLK, &fl);
if (-1 == ret) {
printf("file "%s" locked. proc already exit!!! ", filename);
close(fd);
return 1;
} else {
ftruncate(fd, 0);
char buf[16];
sprintf(buf, "%ld", (long)getpid());
write(fd, buf, strlen(buf) + 1);
//do not close file
return 0;
}
}

























以上是关于linux保证程序单实例运行的主要内容,如果未能解决你的问题,请参考以下文章

Linux - 通过操作文件锁来实现shell script进程单实例

设计模式总结:单例模式

Linux 上的单实例 dotnetcore cli 应用程序

单实例模式

如何创建一个 JVM 全局单例?

iOS之深入解析单例的实现和销毁的底层原理