GitLab maintenance scheduled for Tomorrow, 2020-01-30, from 17:00 to 18:00 CT - Services will be unavailable during this time.

lock.cpp 647 Bytes
Newer Older
Swann Perarnau's avatar
Swann Perarnau committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include <sys/file.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <unistd.h>
#include <stdlib.h>

       //int flock(int fd, int operation);
int main(int argc, char ** argv)
{
	int fd = open("f.lock", O_RDONLY);
	assert(fd != -1);
	printf("%d about to acquire lock!\n", getpid()); fflush(stdout);
	flock(fd, LOCK_EX);
	printf("File is locked by %d!\n", getpid()); fflush(stdout);

	int sleep_time = 1;
	if(argc >= 2)
		sleep_time = atoi(argv[1]);
	sleep(sleep_time);
	flock(fd, LOCK_UN);
	printf("File is unlocked by %d!\n", getpid()); fflush(stdout);
	close(fd);
	return 0;	
}