简体   繁体   English

在Linux下如何检查C中数字返回值的含义?

[英]How does one check the meaning of a numerical return value in C under Linux?

Suppose I'm invoking write() and it returns with the error -8. 假设我正在调用write(),并且返回错误-8。 How can I check which one of the documented error return values this stands for? 如何检查代表的已记录错误返回值之一?

You'd usually use 你通常会用

  man functionname

or perhaps 也许

  man -S2 functionname # specify other section (2, 3, 5, 7)

Most functions that return 0 on success, nonnull on failure, document that they also set errno . 大多数成功返回0的函数,失败返回nonnull的函数说明它们也设置了errno You can get the meaning of the errno global variable 1 您可以获得errno 全局变量 1的含义

  • by looking at errno.h 通过查看errno.h
  • by using the strerror function ( #include <string.h> ) 通过使用strerror函数( #include <string.h>
  • or use the convenient helper perror that prints an error message based on strerror and the prefix given: 或使用方便的帮助程序perror根据strerror和给定的前缀打印错误消息:

      perror("oops, popen failed with: "); 

1 well, it doesn't technically need to be a global variable. 1好,从技术上讲,它不必是全局变量。 Depending on your OS/library it may be a macro, a threadlocal variable, both etc... 取决于您的操作系统/库,它可能是一个宏,一个线程局部变量,两者等等。

Look up the strerror manpage. 查找strerror联机帮助页。 (note, though that write() should only return at worst -1 and the error code in errno ). (请注意,尽管write()仅应在最差的-1处返回,并在errno返回错误代码)。

Formally it is not returning -8, but an error code. 形式上,它不是返回-8,而是错误代码。 These error codes can be found in the manual (eg here: http://linux.die.net/man/2/write ), and you should use these codes to verify if everything went OK. 这些错误代码可以在手册中找到(例如: http : //linux.die.net/man/2/write ),并且您应该使用这些代码来验证是否一切正常。

so, you would use: 因此,您将使用:

 write(..);
if( errno == EFAULT ) { ...}

尝试“ strerror ”和“ errno ”。

You should not print out the return value itself, but strerror(return_value) . 您不应打印出返回值本身,而应打印出strerror(return_value) You can also look at man errno for error description. 您也可以查看man errno以获取错误描述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM