码迷,mamicode.com
首页 > 系统相关 > 详细

linux保证程序单实例运行

时间:2018-11-01 16:55:33      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:fail   get   seek   char   lse   har   usr   tar   roc   

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!!!\n", 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!!!\n", 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保证程序单实例运行

标签:fail   get   seek   char   lse   har   usr   tar   roc   

原文地址:https://www.cnblogs.com/mingzhang/p/9889956.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!