C 中 write(2) 的返回值 0 是错误吗? [英] Is a return value of 0 from write(2) in C an error?

查看:21
本文介绍了C 中 write(2) 的返回值 0 是错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the man page for the system call write(2) -

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

内容如下:

返回值

成功时,字节数写入被返回(零表示什么都没写).出错时,-1 是返回,并设置 errno适当地.如果计数为零并且文件描述符是指常规文件,可能返回 0,或者一个可以检测到错误.对于一个特殊的文件,结果不可移植.

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 仅意味着没有写入任何内容,无论出于何种任意原因.

I would interpret this to mean that returning 0 simply means that nothing was written, for whatever arbitrary reason.

但是,UNP 中的 Stevens 在处理文件描述符时将返回值 0 视为致命错误这是一个 TCP 套接字(这是由另一个函数包装的,该函数在短时间内调用 exit(1) ):

However, Stevens in UNP treats a return value of 0 as a fatal error when dealing with a file descriptor that is a TCP socket ( this is wrapped by another function which calls exit(1) on a short count ):

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 视为合法的返回值.

He only treats 0 as a legit return value if the errno indicates that the call to write was interrupted by the process receiving a signal.

为什么?

推荐答案

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

Stevens probably does this to catch old implementations of write() that behaved differently. For instance, the Single Unix Spec says (http://www.opengroup.org/onlinepubs/000095399/functions/write.html)

这卷IEEE Std1003.1-2001 要求返回 -1 并将 errno 设置为 [EAGAIN],大多数历史实现返回零

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 中 write(2) 的返回值 0 是错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆