Linux下如何捕获错误

Linux中的错误都用宏定义对应着一个整数,叫errno。像下面这样的:

#define	ENAMETOOLONG	63	/* File name too long */
#define	EHOSTDOWN	64	/* Host is down */
#define	EHOSTUNREACH	65	/* No route to host */
#define	ENOTEMPTY	66	/* Directory not empty */

#define	EUSERS		68	/* Too many users */
#define	EDQUOT		69	/* Quota exceeded */
#define	ESTALE		70	/* Stale NFS file handle */
#define	EREMOTE		71	/* Object is remote */

#define	ENOLCK		77	/* No record locks available */
#define	ENOSYS		78	/* Function not implemented */

#define	ENOMSG		80	/* No message of desired type */
#define	EIDRM		81	/* Identifier removed */
#define	ENOSR		82	/* Out of streams resources */
#define	ETIME		83	/* Timer expired */
#define	EBADMSG		84	/* Not a data message */
#define	EPROTO		85	/* Protocol error */
#define	ENODATA		86	/* No data available */
#define	ENOSTR		87	/* Device not a stream */

#define	ENOPKG		92	/* Package not installed */

#define	EILSEQ		116	/* Illegal byte sequence */

这里贴了部分(我下的内核版本是linux-2.6.32.69),具体大家可以去kernel.org下载Linux内核源代码,在errno.h和errno-base.h中进行查看,。


现在你写了如下的管道通信的代码(因为你把管道的读端给关了,还往里写东西,会出错。):

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#define BUFNUM 60
int main() {
	int n;
	int fd[2];
	pid_t pid;
	char buf[BUFNUM];
	signal(SIGPIPE, SIG_IGN);
	pipe(fd);
	close(fd[0]);
	if((n = write(fd[1], "I'm your father.\n", 17)) < 0) {
		printf("%d\n",errno);//输出对应的错误编号
		printf("%s\n",strerror(errno));//返回关于错误编号的描述
	}
	printf("%d\n",n);
}

结果如下:

zhan@ubuntu:~$ ./test1
32
Broken pipe
-1

对应error.h描述如下:

#define EPIPE 32 /* Broken pipe */



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值