gpt4 book ai didi

c - C 中 write(2) 的返回值 0 是错误吗?

转载 作者:IT王子 更新时间:2023-10-29 00:27:42 24 4
gpt4 key购买 nike

在系统调用的手册页中 write(2) -

ssize_t write(int fd, const void *buf, size_t count);

内容如下:

Return Value

On success, the number of bytes written are returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately. If count is zero and the file descriptor refers to a regular file, 0 may be returned, or an error could be detected. For a special file, the results are not portable.

我会将其解释为返回 0 只是意味着没有写入任何内容,无论出于何种原因。

然而,Stevens in UNP在处理作为 TCP 套接字的文件描述符时将返回值 0 视为 fatal error (这由另一个调用 exit(1) 的函数包装):

ssize_t /* Write "n" bytes to a descriptor. */
writen(int fd, const void *vptr, size_t n)
{
size_t nleft;
ssize_t nwritten;
const char *ptr;

ptr = vptr;
nleft = n;
while (nleft > 0) {
if ( (nwritten = write(fd, ptr, nleft)) <= 0) {
if (nwritten < 0 && errno == EINTR)
nwritten = 0; /* and call write() again */
else
return(-1); /* error */
}

nleft -= nwritten;
ptr += nwritten;
}
return(n);
}

只有当 errno 表明对 write 的调用被进程接收信号中断时,他才会将 0 视为合法的返回值。

为什么?

最佳答案

Stevens 这样做可能是为了捕捉旧的实现write() 表现不同。例如,Single Unix 规范说(http://www.opengroup.org/onlinepubs/000095399/functions/write.html)

Where this volume of IEEE Std 1003.1-2001 requires -1 to be returned and errno set to [EAGAIN], most historical implementations return zero

关于c - C 中 write(2) 的返回值 0 是错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2176443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com