C program in Linux: run a single instance

Source: Internet
Author: User
Address: http://blog.chinaunix.net/uid-24622573-id-276141.html

For many services, only one instance can be run on the same server. How can I ensure that only one instance runs at a time? Writing shell scripts to manage the startup and stop of programs is a good method. At startup, the shell script will create a process identification file (the PID of the running instance is stored) to indicate that an instance is running. If the file already exists, it indicates that the existing instance is running, you do not need to do anything. When you exit, the shell script will delete the Process Identity file, indicating that no instance is running.

 

The shell script management method includes another layer on the application. Can you directly determine whether an instance is running when the program starts running? The answer is yes. In fact, the principle is similar. We still need to use public resources-files, of course, not just files, but also support file locks. The general idea is as follows: when the program starts running, it locks a specific file (if it does not exist, it is created). If the lock succeeds, the instance starts to run. If the lock has been occupied, if an instance is running, the program exits directly. In addition, the file lock is also lost after the instance is running. This ensures that only one program instance is running at a time.

 

The procedure is as follows:

1. Open a specific file (such as/var/run/mydaemon. PID), and create it if it does not exist;

2. Use fcntl to apply an advisory lock to the entire area of the file.

3. If the lock is successful, execute the subsequent code and write the PID to the file. If the lock is unsuccessful, an instance is running and exits directly.

 

Implementation example:

# Include <stdio. h>

# Include <stdlib. h>

# Include <unistd. h>

# Include <fcntl. h>

# Include <printf. h>

# Include <string. h>

# Include <errno. h>

# Include <sys/STAT. h>

# Define lockfile "/var/run/mydaemon. PID"

# Define lockmode (s_irusr | s_iwusr | s_irgrp | s_iroth)

 

/* Set advisory lock on file */

Int lockfile (int fd)

{

Struct flock FL;

 

Fl. l_type = f_wrlck;/* write lock */

Fl. l_start = 0;

Fl. l_whence = seek_set;

Fl. l_len = 0; // lock the whole file

 

Return (fcntl (FD, f_setlk, & FL ));

}

 

Int already_running (const char * filename)

{

Int FD;

Char Buf [16];

 

FD = open (filename, o_rdwr | o_creat, lockmode );

If (FD <0 ){

Printf ("can't open % s: % m \ n", filename );

Exit (1 );

}

 

/* Obtain the file lock first */

If (lockfile (FD) =-1 ){

If (errno = eacces | errno = eagain ){

Printf ("file: % s already locked", filename );

Close (FD );

Return 1;

}

Printf ("can't lock % s: % m \ n", filename );

Exit (1 );

}

/* Write the PID of the running instance */

Ftruncate (FD, 0 );

Sprintf (BUF, "% lD", (long) getpid ());

Write (FD, Buf, strlen (BUF) + 1 );

Return 0;

}

 

Int main (INT argc, char * argv [])

{

If (already_running (lockfile ))

Return 0;

/* Add the work code here */

Printf ("START Main... \ n ");

Sleep (100 );

Printf ("Main done! \ N ");

Exit (0 );

}

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.