man page 에 더 잘 나와 있네요.
주의: 한쪽만 fcntl 로 lock 을 걸어서는 의미가 없습니다.
주의: 한쪽만 fcntl 로 lock 을 걸어서는 의미가 없습니다.
| 코드: |
| /*
Copyright (C) Information Equipment co.,LTD. All rights reserved. Code by JaeHyuk Cho <mailto:minzkn@infoeq.com> CVSTAG="$Header$" */ #include <sys/types.h> #include <sys/param.h> /* HZ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> /* errno , EAGAIN , EACCES */ int mz_flock(int s_handle, int s_switch) { int s_result = (-1); struct flock s_flock = {0, }; s_flock.l_type = (s_switch == 0) ? (F_UNLCK) : ((F_RDLCK) | (F_WRLCK)); #if 0 /* optional */ s_flock.l_whence = SEEK_SET; s_flock.l_start = (off_t)0; s_flock.l_len = (off_t)0; s_flock.l_pid = (pid_t)0; #endif do { if(fcntl(s_handle, F_SETLK, (struct flock *)(&s_flock)) != (-1)){ s_result = 1; break; } #if defined(EAGAIN) && defined(EACCES) if((errno != EAGAIN) && (errno != EACCES)) { perror("lock failed"); break; } #endif (void)fprintf(stdout, "Already locked\n"); usleep((1000 / HZ) * 1000); /* HZ=100 , 10 ms */ }while(1); return(s_result); } int main(int s_argc, char **s_argv) { int s_handle; if(s_argc >= 2) { s_handle = open(s_argv[1], O_RDWR); if(s_handle != (-1)) { if(mz_flock(s_handle, 1) > 0) { (void)fprintf(stdout, "LOCK\n"); do{ sleep(1); }while(1); mz_flock(s_handle, 0); /* optional */ (void)fprintf(stdout, "UNLOCK\n"); } else (void)fprintf(stdout, "error\n"); close(s_handle); } else perror(s_argv[1]); } else (void)fprintf(stdout, "usage: %s <file>\n", s_argv[0]); return(0); } /* End of source */ |




댓글을 달아 주세요