Is there a cleaner way to use the write() function reliably?

前端 未结 4 1755
悲哀的现实
悲哀的现实 2021-02-09 16:15

I read the man pages, and my understanding is that if write() fails and sets the errno to EAGAIN or EINTR, I may

4条回答
  •  一向
    一向 (楼主)
    2021-02-09 16:41

    Yes, there are cleaner ways to use write(): the class of write functions taking a FILE* as an argument. That is, most importantly, fprintf() and fwrite(). Internally, these library functions use the write() syscall to do their job, and they handle stuff like EAGAIN and EINTR.

    If you only have a file descriptor, you can always wrap it into a FILE* by means of fdopen(), so you can use it with the functions above.

    However, there is one pitfall: FILE* streams are usually buffered. This can be a problem if you are communicating with some other program and are waiting for its response. This may deadlock both programs even though there is no logical error, simply because fprintf() decided to defer the corresponding write() a bit. You can switch the buffering off, or fflush() output streams whenever you actually need the write() calls to be performed.

提交回复
热议问题