How to prevent a program from running twice in Linux

Source: Internet
Author: User
& Nbsp; implemented through the file lock. at the beginning of the program running, check whether a file exists. If yes, the program is already running, if the file does not exist, use the open statement to create the file. when the program exits, it closes and deletes the file. Staticcharfile_lock [sizeof (ctl_addr.sun _  

The file lock is used to check whether a file exists at the beginning of the program running. If yes, the program is running. If no, the file is created using an open statement, close and delete the file when the program exits.

        
         static char file_lock[sizeof(ctl_addr.sun_path)] = /var/run/file.pid;  static bool file_lock_created = FALSE;    static int  create_lock(void)  {   int fd = open(file_lock, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC,   S_IRUSR | S_IRGRP | S_IROTH);     if (fd < 0)   {   if (errno == EEXIST)   {   fprintf(stderr, "file: lock file "%s" already exists", file_lock);   exit_file(10);   }   else   {   fprintf(stderr, "file: unable to create lock file "%s" (%d %s)"   , file_lock, errno, strerror(errno));   exit_file(1);   }   }   file_lock_created = TRUE;   return fd;  }    static bool  fill_lock(int lockfd)  {   char buf[30]; /* holds "" */   pid_t pid;   int len;     pid = getpid();   len = snprintf(buf, sizeof(buf), "%u", (unsigned int) pid);   bool ok = len > 0 && write(lockfd, buf, len) == len;     close(lockfd);   return ok;  }    static void  delete_lock(void)  {   if (file_lock_created)   {   //delete_ctl_socket();   unlink(file_lock); /* is noting failure useful? */   }  }
        

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.