近期找了多种c语言实现让程序只运行一个进程实例方法,只有一种最合适。
#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
#include<string.h>
#define LOCKFILE ".lock"
int lockfile(int fd)
{
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_start = 0;
fl.l_whence = SEEK_SET;
fl.l_len = 0;
return fcntl(fd, F_SETLK, &fl);
}
int already_running(void)
{
int fd;
char buf[16];
fd = open(LOCKFILE, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if(fd < 0)
{
fprintf(stderr, "FAILED TO OPEN FILE" LOCKFILE);
exit(1);
}
if(lockfile(fd) < 0)
{
if(EACCES == errno || EAGAIN == errno)
{
close(fd);
return 1;
}
fprintf(stderr, "FAILED TO LOCK FILE" LOCKFILE);
exit(1);
}
ftruncate(fd, 0);
sprintf(buf, "%ld", (long)getpid());
write(fd, buf, strlen(buf) + 1);
return 0;
}
int main()
{
if(already_running())
{
fprintf(stderr, "PROGRAM ALREADY RUNNING...\n");
exit(0);
}
while(1)
{
sleep(1);
printf("INPUT CTRL+C TO KILL ME!\n");
}
return 0;
}
编译运行
root@ubuntu:/home/per/demo# gcc msg3.c -o msg3
root@ubuntu:/home/per/demo# ./msg3
INPUT CTRL+C TO KILL ME!
INPUT CTRL+C TO KILL ME!
INPUT CTRL+C TO KILL ME!
INPUT CTRL+C TO KILL ME!
root@ubuntu:/home/per/demo# ./msg3
PROGRAM ALREADY RUNNING...
root@ubuntu:/home/per/demo#
其他有问题方法,最主要是需要释放资源才能重新申请等方法,都不太可行。
下面这个方法,如果遇到程序异常退出或者Ctrl+C退出,则程序无法启动。
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
#define SEM_NAME "/my_semaphore"
int lock_instance() {
sem_t *sem;
int fd;
int rc;
int value;
// 创建或打开一个命名信号量
sem = sem_open(SEM_NAME, O_CREAT, 0644, 1);
printf("sem_open.\n");
if (sem == SEM_FAILED) {
perror("Failed to create semaphore");
return -1;
}
// 获取信号量锁
rc = sem_wait(sem);
printf("sem_wait rc:[%d].\n", rc);
if (rc == -1) {
perror("Failed to lock semaphore");
sem_close(sem);
return -1;
}
// 获取成功,返回信号量句柄
fd = sem_getvalue(sem, &value);
printf("sem_getvalue.fd:%d value:%d\n", fd, value);
return fd;
}
int unlock_instance(int fd) {
sem_t *sem;
int rc;
// 获取信号量句柄
sem = sem_open(SEM_NAME, O_CREAT, 0644, 1);
printf("unlock_instance sem_open.\n");
if (sem == SEM_FAILED) {
perror("Failed to create semaphore");
return -1;
}
// 释放信号量锁
rc = sem_post(sem);
printf("unlock_instance sem_post.\n");
if (rc == -1) {
perror("Failed to unlock semaphore");
sem_close(sem);
return -1;
}
// 释放成功,关闭信号量句柄并删除命名信号量
sem_close(sem);
printf("unlock_instance sem_close.\n");
sem_unlink(SEM_NAME);
printf("unlock_instance sem_unlink.\n");
return 0;
}
int main() {
printf("main.\n");
int fd = lock_instance();
if (fd == -1) {
printf("Another instance is running.\n");
return 1;
}
printf("This is the only instance.\n");
// 程序正常退出时释放锁
atexit(unlock_instance);
printf("sleep 6s.\n");
sleep( 6 );
printf("exit.\n");
return 0;
}