Why isn't the file lock released on close() if I launch a process while the file is locked?
Question: If I open a file, acquire a lock, then close the file:

    
    
    import fcntl
    file = open("some_file", "w")
    fcntl.flock(file.fileno(), fcntl.LOCK_EX)
    file.close()
    

The file lock is released immediately when the file is closed, which is what I
would expect.

However, if I launch a background process while the file is locked:

    
    
    import fcntl
    import subprocess
    file = open("some_file", "w")
    fcntl.flock(file.fileno(), fcntl.LOCK_EX)
    subprocess.Popen(["python", "-c", "import time; time.sleep(10.0)"])
    file.close()
    

The above code exits immediately, but the file lock is not released until the
background process has finished. If I run the above code and then immediately
run it a second time, the second instance blocks for ten seconds. Why isn't
the lock released?

I know I can explicitly release the lock by calling flock() with LOCK_UN, but
that's not what I'm asking. My question is, why does launching a background
process prevent close() from releasing the file lock?


Answer: The child process inherits file descriptors from the parent. And the "locking"
might be shared for the same file between different OS processes (that is the
point of the locking).

You could specify `close_fds=True` to close the file in the child too.
`close_fds=True` is the default on POSIX systems in Python 3.

Newly created file descriptors are non-inheritable by default since Python
3.4. See [PEP 446](https://docs.python.org/3/whatsnew/3.4.html#whatsnew-
pep-446).

