在Linux下,如果不加限制,同一个程序,可以有多个运行实例,也称之为进程.它们都有一样的名字,执行着一样的代码段.不同的是,它们拥有不同的pid以及进程空间.有时候,希望同一时间只能创建一个进程.下面这段示例代码就加了这样一个限制.
核心点:
1. 进程在启动时,判断/tmp/my_pid_file是否存在;如果不存在,则将当前进程的pid写入,程序继续运行;
2. 如果/tmp/my_pid_file已经存在但无内容,则将当前进程的pid写入,程序继续运行;
3. 如果/tmp/my_pid_file已经存在且有内容,读取并判断该值指向的pid是否正在运行。如果没有,则将当前进程的pid写入,程序继续运行;否则,当前进程退出。使用了 kill(pid, 0) 进行检测.
4. 在收到SIGINT和SIGTERM时,先删除/tmp/my_pid_file,再退出.
single_app.c:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#define MY_PID_FILE "/tmp/my_pid_file"
#define BUF_LEN_FOR_PID 64
static int write_pid_into_fd(int fd, pid_t pid)
{
int ret = -1;
char buf[BUF_LEN_FOR_PID] = {0};
/* Move cursor to the start of file. */
lseek(fd, 0, SEEK_SET);
sprintf(buf, "%d", pid);
ret = write(fd, buf, strlen(buf