曲径通幽论坛

标题: 处理系统调用中的错误 [打印本页]

作者: beyes    时间: 2008-11-16 23:04
标题: 处理系统调用中的错误
如 open 无法打开指定的文件,read 无法读取,lseek 无法指定指针的位置..此类情况都会返回 -1,-1 是表示在系统调用中出了些问题。调用者每次都必须检查返回值,一旦检测到相应的错误,必须作出相应的处理。

  系统调用会遇到哪些错误呢?每个系统调用都有自己的错误集。如 open 调用,加入要打开的文件不存在,或者虽然存在,但没有读取的权限,或者打开的文件太多,都会导致报错。那如何来确定发生了哪一种错误呢?

  1、确定错误的种类: errno

内核通过全局变量 errno 来指明错误类型,每个程序都可以访问到这个变量。

#define  EPERM    1  /* Operation not permitted */
#define  ENOENT  2  /* No such file or directory */
#define  ESRCH    3  /* No such process */
#define  EINTR    4  /* Interrupted system call */
#define  EIO      5  /* I/O error */

  2、信息错误的提示 perror()

函数 perror( string ) 会自己查找错误代码,在标准错误输出中显示出相应的错误信息,参数 string 是要同时显示出的描述性信息。例如:

int sample()
{
    int fd;
    fd = open("file", O_RDONLY);
    if( fd == -1 )
  {
      perror("Cannot open file");
      return;
  }
...
}
当有错误发生时,可能会看到下面的信息:

Cannot open file: No such file or directory
Cannot open file: Interrupted system call




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2