How to make the program unable to start repeatedly under linux

Usually a program can be executed multiple times, and there are multiple identical processes. Sometimes we only allow a single process to access some global resources. In order to prevent multiple processes, we need to implement the method that a process can only have one instance on a machine. 
After searching, you can use the flock method to build a lock file, and let the program check whether there is an instance in execution before executing it, that is, lock the file.

single_program.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>

int main()
{
  int lock_file = open("/tmp/single_proc.lock", O_CREAT|O_RDWR, 0666);
  int rc = flock(lock_file, LOCK_EX|LOCK_NB);
  if (rc)
  {
    if (EWOULDBLOCK == errno)
    {
      printf("该实例已经运行!\nExit...");
    }
  }
  else
  {
    char buffer[64];
    sprintf(buffer, "pid:%d\n", getpid());
    write(lock_file, buffer, strlen(buffer));
    printf("已启动新实例,输入任何字符退出...\n");

    scanf("%s",buffer);
    printf("Exit\n",buffer);
    close(lock_file); // 不要忘记释放文件指针
  }
  exit(0);
}

 

Running result 
[root@centos6 data]# gcc single_program.c -o single_program 
[root@centos6 data]# ./single_program 
has started a new instance, enter any character to exit...

The above program will block and wait, then open a new terminal, and execute the program 
[root@centos6 data]# ./single_program 
The instance is already running, exit! 
[root@centos6 data]# 
You can see that the program exits as soon as it starts. Viewing the lock file 
[root@centos6 data]# cat /tmp/single_proc.lock 
pid:7162 
indicates that a global lock file has been added, and a new process cannot be started. View the started process 
[root@centos6 data]# ps -ef|grep -v grep|grep single_program 
root 7162 6521 0 22:13 pts/0 00:00:00 ./single_program 
really has only one process, in this way we It can be used in some special scenarios where only a single process is allowed to be started on one machine.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325696283&siteId=291194637