fcntl로 file locking하는 프로그램입니다.

feelpassion의 이미지

unix09A.txt라는 파일은 00 이렇게 숫자 두개만 있습니다. 하나의 프로세스는 readlock을 앞의 0에 걸어놓고 읽기만 하고, 두 번째 프로세스는 writelock을 뒤의 0에 걸어놓고 읽고, +1한 숫자를 쓰는 프로그램입니다.
이상하게도 +1한 숫자가 계속 그뒤 아무것도 없는자리에 써집니다. 그러니까 unix09A.txt파일에는 001이 남는거죠... 01만 남게 할 순 없나요? lseek()함수를 제대로 쓴 것 같은데 왜 안되는지 모르겠습니다. 프로그램을 두번 돌리면 02가 되어야겠죠....
고수님들 부탁드립니다~

//unix09A file locking program
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char ** argv)
{
	int fd, retval, nread;
	char buf[1];
	struct flock my_lock;

	if( (fd=open("unix09A.txt",O_RDWR))== -1){
		perror("open()");
		exit(1);
	}

	switch(fork()){
	case -1:
		perror("fork()");
		exit(2);
		
	case 0: //byte #0
		my_lock.l_type = F_RDLCK;
		my_lock.l_whence = SEEK_SET;
		my_lock.l_start = 0;
		my_lock.l_len = 1;	
		retval = fcntl(fd, F_SETLKW, &my_lock); 	
		if(retval == -1){
			perror("byte #0: locking");
			exit(3);
		}
		
		printf("byte #0: read locked\n");
		read(fd, buf, 1);
		printf("byte #0: read result = %d\n", buf[0]);
		sleep(3);
		my_lock.l_type = F_UNLCK;
		if( (fcntl(fd, F_SETLK, &my_lock))== -1){
			perror("byte #0: unlocking");
			exit(4);
		}
		printf("byte #0: unlocked\n");
		exit(0);
	
	default: //byte #1
		my_lock.l_type = F_WRLCK;
		my_lock.l_whence = SEEK_SET;
		my_lock.l_start = 1;
		my_lock.l_len = 1;
		retval = fcntl(fd, F_SETLKW, &my_lock);
		if( retval == -1 ){
			perror("byte #1: locking");
			exit(5);
		}
		printf("byte #1: write locked\n");
		
		lseek(fd, SEEK_SET, 1); //읽어들일 위치를 정한다.
		nread = read(fd, buf, 1);
		printf("byte #1: read result = %d\n", buf[0]);
		buf[0] = buf[0] + 1;
		lseek(fd, SEEK_SET,1);
		write(fd, buf, 1);
		printf("byte #1: write result = %d\n",buf[0]);
		sleep(3);
		my_lock.l_type = F_UNLCK;
		if( (fcntl(fd, F_SETLK, &my_lock)) == -1 ){
			perror("byte #1: unlocking");
			exit(6);
		}
		printf("byte #1: unlocked\n");
		exit(0);
	}
}
sangwoo의 이미지

먼저, lseek()의 문법이 틀렸습니다. lseek(fd, 1, SEEK_SET) 과 같은 식으로
사용하셔야 합니다. SEEK_SET은 보통 0으로 정의되어 있으므로, 올려주신
프로그램에서는 실제로 lseek(fd, 0, SEEK_CUR)를 하고 있는 셈입니다.

참고로, fork() 로 생성된 프로세스들은 open된 파일 디스크립터에 대해서 오프셋을
공유합니다. 이 프로그램에서는 우연히 영향을 받지는 않지만, 만일 parent 가 write
전에 lseek한 후, child가 한 바이트를 읽게 되면, 읽은 후 파일 디스크립터의 오프셋이
*우연히* 1로 변합니다. 만일 child가 두 바이트 이상을 읽는다면 문제가 발생합니다. 두번째 문제의 해결책으로는.. fork()후에 각각 open()을 하시면 되겠습니다.

----
Let's shut up and code.

feelpassion의 이미지

앗 이런....쪽팔리는 일이...^^;; 죄송합니다~^^;;;;;
귀찮아서 기억나는대로 했더만 이런 일이 생기는군요...헐~
감사합니다~

남으로 창을 내겠소.
밭이 한참갈이 괭이로 파고 호미론 김을 메지요.
구름이 꼬인다 갈리있소. 새들의 노래는 공으로 들으랴오.
강냉이가 익거든 와자셔도 좋소.
왜 사냐건 웃지요.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.