접기
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void) {
int fd, val;
pid_t pid;
char buf[10];
struct stat statbuf;
struct flock lock;
fd = open("lockfile", O_RDWR | O_CREAT | O_TRUNC, 0644);
if (fd < 0) {
perror("open error");
return -1;
}
if (write(fd, "aaa", 3) != 3) {
perror("write error");
return -1;
}
if (fstat(fd, &statbuf) < 0) {
perror("write error");
return -1;
}
if (fchmod(fd, (statbuf.st_mode & ~S_IXGRP) | S_ISGID) < 0) {
perror("write error");
return -1;
}
if ((pid = fork()) < 0) {
perror("write error");
return -1;
}
if (pid > 0) {
printf("parent 1\n");
lock.l_type = F_WRLCK;
lock.l_start = 0;
lock.l_whence = SEEK_SET;
lock.l_len = 0;
if (fcntl(fd, F_SETLK, &lock) < 0) {
perror("write error");
return -1;
}
printf("parent 2\n");
sleep(10);
printf("parent 3\n");
if (waitpid(pid, NULL, 0) < 0) {
perror("write error");
return -1;
}
printf("parent 4\n");
} else {
printf("child 1\n");
sleep(10);
printf("child 2\n");
val = fcntl(fd, F_GETFL, 0);
if (val < 0) {
perror("write error");
return -1;
}
val |= O_NONBLOCK;
if (fcntl(fd, F_SETFL, &lock) < 0) {
perror("fcntl error");
return -1;
}
printf("child 3\n");
lseek(fd, 0, SEEK_SET);
if (read(fd, buf, 6) < 0) {
perror("read error");
return -1;
}
printf("child 4\n");
printf ("read success!!");
}
return 1;
}
접기
접기
struct flock {
short l_type; /* F_RDLCK, F_WRLCK, or F_UNLCK */
off_t l_start; /* offset in bytes, relative to l_whence */
short l_whence; /* SEEK_SET, SEEK_CUR, or SEEK_END */
off_t l_len; /* length, in bytes; 0 means lock to EOF */
pid_t l_pid; /* returned with F_GETLK */
};
접기