(GO) Linux with file lock implementation to ensure that a program can only start a process

Source: Internet
Author: User

#include <stdio.h>

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

int main (int argc,char* argv[])
{
int FD;
int Lock_result;
struct flock lock;
char * pfilename = "Tmp.lck";
FD = open (PFILENAME,O_RDWR);
if (fd<0)
{
printf ("Open file failed.\n");
return 1;
}
Lock_result = LOCKF (fd,f_test,0); Parameter uses F_lock, if it is already locked, it blocks until the previous process releases the lock, and the parameter 0 indicates that the entire file is locked
Return 0 means unlocked or locked by the current process; 1 indicates lock by other process
if (lock_result<0)
{
Perror ("Exec lockf function failed.\n");
return 1;
}

Lock_result = LOCKF (fd,f_lock,0); Parameter uses F_lock, if it is already locked, it blocks until the previous process releases the lock, and the parameter 0 indicates that the entire file is locked
if (lock_result<0)
{
Perror ("Exec lockf function failed.\n");
return 1;
}

printf ("Pid:%ld process locked The file.\n", (long) getpid ());

Do something
while (GetChar () <0);

printf ("Pid:%ld Process Release The file.\n", (long) getpid ());
return 0;

(GO) Linux with file lock implementation to ensure that a program can only start a process

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.