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? */ } } |