gpt4 book ai didi

c - 检查读写系统调用的返回值的最佳方法是什么?

转载 作者:行者123 更新时间:2023-11-30 14:34:47 25 4
gpt4 key购买 nike

我有兴趣找出检查 Linux 上读写系统调用返回值的最佳方法。根据手册页,例如用于写入:

Upon successful completion, write() and pwrite() shall return the number of bytes actually written to the file associated with fildes. This number shall never be greater than nbyte. Otherwise, -1 shall be returned and errno set to indicate the error.

供阅读:

On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. On error, -1 is returned, and errno is set appropriately. In this case it is left unspecified whether the file position (if any) changes.

这让我想知道:

if (ret < 0) {
// see strerror
}

if (ret == -1) {
// see strerror
}

哪一条路是该走的路,为什么?根据手册页,在我看来,从功能角度来看,这些是完全相同的。这样对吗?我猜唯一的区别是第一个语句应该使用比较器,这将需要更多的资源。我的这个假设正确吗?请与我分享您的想法。谢谢

最佳答案

首先,我将使用 gcc 9.2 (x86-64) 考虑性能:

#include <stdio.h>

int main(int argc, char **args, char **env) {
if (argc < 0) {
printf("ERROR!");
}

return 0;
}

会生成类似的东西

.LC0:
.string "ERROR!"
main:
push rbp
mov rbp, rsp
sub rsp, 32
mov DWORD PTR [rbp-4], edi
mov QWORD PTR [rbp-16], rsi
mov QWORD PTR [rbp-24], rdx
cmp DWORD PTR [rbp-4], 0
jns .L2
mov edi, OFFSET FLAT:.LC0
mov eax, 0
call printf
.L2:
mov eax, 0
leave
ret

#include <stdio.h>

int main(int argc, char **args, char **env) {
if (argc == -1) {
printf("ERROR!");
}

return 0;
}

生成

.LC0:
.string "ERROR!"
main:
push rbp
mov rbp, rsp
sub rsp, 32
mov DWORD PTR [rbp-4], edi
mov QWORD PTR [rbp-16], rsi
mov QWORD PTR [rbp-24], rdx
cmp DWORD PTR [rbp-4], -1
jne .L2
mov edi, OFFSET FLAT:.LC0
mov eax, 0
call printf
.L2:
mov eax, 0
leave
ret

所以在性能方面没有任何差异。使用此编译器和架构。

其他纯属个人意见。我个人会选择“< 0”......只是因为它捕获了所有内容。

关于c - 检查读写系统调用的返回值的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58833212/

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