What happens if a write system call is called on same file by 2 different processes simultaneously

前端 未结 5 1143
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-17 05:53

Does the OS handle it correctly?

Or will I have to call flock()?

5条回答
  •  天涯浪人
    2020-12-17 06:12

    write(), writev(), read(), readv() can generate partial writes/reads where the amount of data transferred is smaller than what was requested.

    Quoting the Linux man page for writev():

    Note that is not an error for a successful call to transfer fewer bytes than requested

    Quoting the POSIX man page:

    If write() is interrupted by a signal after it successfully writes some data, it shall return the number of bytes written.

    AFAIU, O_APPEND does not help in this regard because it does not prevent partial writes: it only ensures that whatever data is written is appended at the end of the file.

    See this bug report from the Linux kernel:

    A process is writing a messages to the file. [...] the writes [...] can be split in two. [...] So if the signal arrives [...] the write is interrupted. [...] this is perfectly valid behavior as far as spec (POSIX, SUS,...) is concerned

    FIFOs and PIPE writes smaller than PIPE_MAX however are guaranteed to be atomic.

提交回复
热议问题