什么时候应该使用PERROR(QUOT; ...")和fprintf(标准错误," ...")?

问题描述:

读手册页和一些code并没有真正帮助我
理解之间的区别 - 或者更好,我应该使用 - PERROR(...) fprintf中(标准错误,... )

Reading the man pages and some code did not really help me in understanding the difference between - or better, when I should use - perror("...") or fprintf(stderr, "...").

调用 PERROR 会给你的相互preTED值错误号,这是由系统调用POSIX写入线程局部误差值(即每个线程都有它的自身价值的errno )。例如,如果您对的open(),并且有产生的(也就是说,它返回 -1错误$ C $通话C>),你可以再调用 PERROR 随即看到什么实际的错误了。请记住,如果你在此期间调用其他系统调用,然后在错误号的值将被覆盖,并呼吁 PERROR 不会有任何用处的,如果是由系统调用较早产生的错误诊断您的问题。

Calling perror will give you the interpreted value of errno, which is a thread-local error value written to by POSIX syscalls (i.e., every thread has it's own value for errno). For instance, if you made a call to open(), and there was an error generated (i.e., it returned -1), you could then call perror immediately afterwards to see what the actual error was. Keep in mind that if you call other syscalls in the meantime, then the value in errno will be written over, and calling perror won't be of any use in diagnosing your issue if an error was generated by an earlier syscall.

fprintf中(标准错误,...)另一手可以用来打印自己的自定义错误消息。通过打印到标准错误,您避免错误报告输出正常的输出应该会标准输出被复用

fprintf(stderr, ...) on the other-hand can be used to print your own custom error messages. By printing to stderr, you avoid your error reporting output being muxed with "normal" output that should be going to stdout.

请记住, fprintf中(标准错误,%S \\ n字符串错误(错误))类似于 PERROR(NULL)因为调用字符串错误(错误)将生成错误号打印的字符串值>和那么你就可以结合,与通过 fprintf中的任何其他自定义错误消息

Keep in mind that fprintf(stderr, "%s\n", strerror(errno)) is similar to perror(NULL) since a call to strerror(errno) will generate the printed string value for errno, and you can then combined that with any other custom error message via fprintf.