How to prevent a program from running twice in Linux

Source: Internet
Author: User
Article Title: how to prevent a program from being run twice in Linux. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.

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 \ n", file_lock );
Exit_file (10 );
}
Else
{
Fprintf (stderr, "file: unable to create lock file \" % s \ "(% d % s) \ n"
, File_lock, errno, strerror (errno ));
Exit_file (1 );
}
}
File_lock_created = TRUE;
Return fd;
}
  
Static bool
Fill_lock (int lockfd)
{
Char buf [30];/* holds "\ n "*/
Pid_t pid;
Int len;
  
Pid = getpid ();
Len = snprintf (buf, sizeof (buf), "% u \ n", (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? */
}
}

Related Article

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.