unix中的获取最后错误原因,一般都从errno得到,而且大部分书或者资料都说是全局的
这个全局的真不好理解,到底会不会进程(线程)安全的,答案应该是肯定的,因为看了不少程序都这么用的,否则在这些程序中早就出问题了,那不是说全局的,怎么会没问题呢?
首先看下errno.h头文件定义了:
#if defined(_REENTRANT) || defined(_TS_ERRNO) || _POSIX_C_SOURCE - 0 >= 199506L
extern int *___errno();
#define errno (*(___errno()))
#else
extern int errno;
就是说当定义了某些宏后,errno就变成一个函数定义了,会从局部变量中取得,如果没定义宏,就仍旧是一个变量!
这可能还不好懂:
最后看了下perror(),strerror()函数的介绍
man perror
里面有这么一段:
In the case of multithreaded applications, the -mt option
must be specified on the command line at compilation time
(see threads(5)). When the -mt option is specified, errno
becomes a macro that enables each thread to have its own
errno. This errno macro can be used on either side of the
assignment as though it were a variable.
现在大概明白了,这个errno该怎么用了!从进程来说肯定是安全,隔离的。。。赫赫
从多线程来说,需要指定参数,来进行宏定义
最后在补充下shell中的$? 变量,获取最后一条脚本的运行结果0,成功;1,失败
也是安全的!经过在两个同名终端上测试,一个程序中调用shell测试。。。基本可靠了。。。