您的位置 首页 传感器

在Linux下避免某个程序被运转两次的办法

通过文件锁来实现,在程序运行的一开始,检查某文件是否存在,如果存在则说明改程序已经在运行了,如果不存在则利用open语句创建该文件,程序退出

经过文件锁来完成,在程序运转的一开始,查看某文件是否存在,假如存在则阐明改程序现已在运转了,假如不存在则使用open句子创立该文件,程序退出时封闭并删去此文件。

static char file_lock[sizeof(ctl_addr.sun_path)] = /var/run/file.pid;

static bool file_lock_created = FALSE;

static int

create_lock(void)

{

int fd = open(file_lock, O_WRONLY   O_CREAT   O_EXCL   O_TRUNC,

S_IRUSR   S_IRGRP   S_IROTH);

if (fd 0)

{

if (errno == EEXIST)

{

fprintf(stderr, file: lock file \%s\ already exists\n, file_lock);

exit_file(10);

}

else

{

fprintf(stderr, file: unable to create lock file \%s\ (%d %s)\n

, file_lock, errno, strerror(errno));

exit_file(1);

}

}

file_lock_created = TRUE;

return fd;

}

static bool

fill_lock(int lockfd)

{

char buf[30]; /* holds \n */

pid_t pid;

int len;

pid = getpid();

len = snprintf(buf, sizeof(buf), %u\n, (unsigned int) pid);

bool ok = len > 0 write(lockfd, buf, len) == len;

close(lockfd);

return ok;

}

static void

delete_lock(void)

{

if (file_lock_created)

{

//delete_ctl_socket();

unlink(file_lock); /* is noting failure useful? */

}

}

声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/yingyong/chuanganqi/297943.html

为您推荐

联系我们

联系我们

在线咨询: QQ交谈

邮箱: kf@86ic.com

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部