在Linux 系统中/var/run下有不少以pid结尾的文件,这个实际上是为了保证程序以单例模式运行而设计的。程序在启动后,首先打开(若是没有则建立)/var/run/xx.pid,而后尝试去设置文件锁,若是成功,则将程序的进程ID写入该文件,写入后注意不要关闭文件或解锁;若是加锁失败,代表程序已经有一个进程在运行了,则退出这次启动。此机制在一些程序尤为是服务器程序中很常见,例如sip 服务器kamailio中就是这样保证程序以单例模式运行的。服务器
注:程序退出后,文件锁自动解锁。spa
#include
#include
#include
#include
#define DEFAULT_FILE "/var/run/test.pid"
int main(int argc, char *argv[])
{
int fd = -1;
char buf[32];
fd = open(DEFAULT_FILE, O_WRONLY | O_CREAT, 0666);
if (fd < 0) {
perror("Fail to open");
exit(1);
}
struct flock lock;
bzero(&lock, sizeof(lock));
if (fcntl(fd, F_GETLK, &lock) < 0) {
perror("Fail to fcntl F_GETLK");
exit(1);
}
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
if (fcntl(fd, F_SETLK, &lock) < 0) {
perror("Fail to fcntl F_SETLK");
exit(1);
}
pid_t pid = getpid();
int len = snprintf(buf, 32, "%d\n", (int)pid);
write(fd, buf, len); //Write pid to the file
printf("Hello world\n");
while(1);
return 0;
}
编译:
gcc -o test test.c设计
运行:code
1. 打开终端: ./test进程
cat /var/run/test.pid23409ip
2. 打开另外一终端:./test,打印错误以下get
Fail to fcntl F_SETLK: Resource temporarily unavailablestring
表示程序已经有实例运行it