Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 27 Nov 1997 22:43:01 -0700 (MST)
From:      Charles Mott <cmott@srv.net>
To:        hackers@freebsd.org
Subject:   flock() question
Message-ID:  <Pine.BSF.3.96.971127223541.29176B-100000@darkstar.home>

next in thread | raw e-mail | index | archive | help
Below are two test programs.  What I observe is that if a file descriptor
is opened and a process forks, then advisory locking does not appear to
work.  On the other hand, if the process forks, and then the file is
opened independently by each process, advisory locking works perfectly
well.

Is this correct?  From reading the man page on flock(2), I would have
guessed that locking would have worked in both situations.  I am running
2.2.2-R.

  -- Charles Mott

*** Test 1: open() before fork() ***
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/file.h>

main()
{
    int fd;

    fd = open("locktest", O_WRONLY | O_CREAT, 0644);

    fork();

    for (;;)
    {
        printf("(1) pid=%d\n", getpid());
        flock(fd, LOCK_EX);
        printf("(2) pid=%d\n", getpid());
        sleep(5);
        printf("(3) pid=%d\n", getpid());
        flock(fd, LOCK_UN);
    }
}


*** Test 2: open() after fork() ***
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/file.h>

main()
{
    int fd;

    fork();

    fd = open("locktest", O_WRONLY | O_CREAT, 0644);

    for (;;)
    {
        printf("(1) pid=%d\n", getpid());
        flock(fd, LOCK_EX);
        printf("(2) pid=%d\n", getpid());
        sleep(5);
        printf("(3) pid=%d\n", getpid());
        flock(fd, LOCK_UN);
    }
}




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?Pine.BSF.3.96.971127223541.29176B-100000>