Skip to content

Instantly share code, notes, and snippets.

@justdoit0823
Last active August 28, 2017 11:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justdoit0823/78888405f515cd0d5f90b09cf4510b00 to your computer and use it in GitHub Desktop.
Save justdoit0823/78888405f515cd0d5f90b09cf4510b00 to your computer and use it in GitHub Desktop.
how file lock is handled in child process.
  • File Record lock

As well as being removed by an explicit F_UNLCK, record locks are automatically released when the process terminates or if it closes any file descriptor referring to a file on which locks are held. This is bad: it means that a process can lose the locks on a file like /etc/passwd or /etc/mtab when for some reason a library function decides to open, read and close it.

Record locks are not inherited by a child created via fork(2), but are preserved across an execve(2).

Because of the buffering performed by the stdio(3) library, the use of record locking with routines in that package should be avoided; use read(2) and write(2) instead.

  • Fork

The child process shall have its own copy of the parent's file descriptors. Each of the child's file descriptors shall refer to the same open file description with the corresponding file descriptor of the parent. File locks set by the parent process shall not be inherited by the child process.

  • execve

By default, file descriptors remain open across an execve(). File descriptors that are marked close-on-exec are closed; see the description of FD_CLOEXEC in fcntl(2). (If a file descriptor is closed, this will cause the release of all record locks obtained on the underlying file by this process. See fcntl(2) for details.) POSIX.1-2001 says that if file descriptors 0, 1, and 2 would otherwise be closed after a successful execve(), and the process would gain privilege because the set-user_ID or set-group_ID permission bit was set on the executed file, then the system may open an unspecified file for each of these file descriptors. As a general principle, no portable program, whether privileged or not, can assume that these three file descriptors will remain closed across an execve().

  • posix_spawn

For those file descriptors that remain open, all attributes of the corresponding open file descriptions, including file locks (see fcntl()), shall remain unchanged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment