For example, say I have the following shell command.
~]$ foobar 2>> foobar.log
The above command redirects the standard error output (stderr
, or file descriptor 2
) to the file foobar.log
, appending the output (the >>
rather than just >
).
Now, assume that two users are both running the exact same command. In this case, the output to the file is interleaved, making it rather difficult to read.
Programs can utilise "advisory file locking" (via the fcntl()
C function) as a operating-system level mutual-exclusion on files, essentially coordinating the multiple process so that only one process writes to the file at any given time. Hence the output of the two processes is no longer interleaved and becomes easier to read.
However, how do shells implement the invocation above? If they use the pipe()
system call, advisory file locking will not work. If, on the other hand, they use dup()
(or some other variant) before calling fork()/exec()
, then advisory file locking should work.
Which is the case, and should advisory file locking work on shell-redirected standard output (stdout
, file descriptor 1) and standard error (stderr
, file descriptor 2)?