让程序最多只能有一个实例在运行(文件独占)
通过文件独占的方式,我们打开指定的文件后,用 lockf 对文件加锁,结束程序时解锁文件。
下面代码中我们将当前程序的 PID 写入文件。
int writePidFile(const char *pidFile) {
char str[32];
int fd = open(pidFile, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
if (fd < 0) {
printf("Can't open pidFile %s.\n", pidFile);
exit(1);
}
// Lock pidFile.
if (lockf(fd, F_TLOCK, 0)) {
printf("Can't lock pidFile %s.\n", pidFile);
exit(0);
}
sprintf(str, "%d\n", getpid());
// Write pid to pidFile.
ssize_t len = strlen(str);
if (write(fd, str, len) != len) {
printf("Can't write pidFile %s.\n", pidFile);
exit(0);
}
printf("Wrote pid file %s.\n", pidFile);
return fd;
}
int main(){
int pid_fd = writePidFile("server.pid");
...
lockf(pid_fd, F_ULOCK, 0);
close(pid_fd);
}
┆凉┆暖┆降┆等┆幸┆我┆我┆里┆将┆ ┆可┆有┆谦┆戮┆那┆ ┆大┆始┆ ┆然┆
┆薄┆一┆临┆你┆的┆还┆没┆ ┆来┆ ┆是┆来┆逊┆没┆些┆ ┆雁┆终┆ ┆而┆
┆ ┆暖┆ ┆如┆地┆站┆有┆ ┆也┆ ┆我┆ ┆的┆有┆精┆ ┆也┆没┆ ┆你┆
┆ ┆这┆ ┆试┆方┆在┆逃┆ ┆会┆ ┆在┆ ┆清┆来┆准┆ ┆没┆有┆ ┆没┆
┆ ┆生┆ ┆探┆ ┆最┆避┆ ┆在┆ ┆这┆ ┆晨┆ ┆的┆ ┆有┆来┆ ┆有┆
┆ ┆之┆ ┆般┆ ┆不┆ ┆ ┆这┆ ┆里┆ ┆没┆ ┆杀┆ ┆来┆ ┆ ┆来┆