[Binoculars:Logger/sortMD5.c]
进行log dump的时候,初始化fd,系统默认赋值0.
int i, j, z, fd,score = 0, fblog = 0;
...
if ((fd = open(URL_MISS_LOG, O_CREAT|O_WRONLY, S_IRWXU | S_IRGRP | S_IROTH )) == 0) { fprintf(stderr,"ERROR: Problems opening %s for writing\n",URL_MISS_LOG); canMiss = 0; }
...
if(canCal){ if ((fblog = open(FEEDBACK_LOG, O_CREAT|O_WRONLY, S_IRWXU | S_IRWXG | S_IROTH )) == 0) { fprintf(stderr,"ERROR: Problems opening %s for writing, filter won't be carried out\n",FEEDBACK_LOG); canFilter = 0; }
...
close(fblog); close(fd);
...
if ((fd = open(MD5_HIT_LOG, O_CREAT|O_WRONLY, S_IRWXU | S_IRGRP | S_IROTH )) == 0) { fprintf(stderr,"ERROR: Problems opening %s for writing\n",MD5_HIT_LOG); exit(1); }
...
|
如果canCal=0(即feedback adding loop被turn off的时候),那么fblog将会很危险,因为这时fblog=0,依旧是初始化时的值。
不幸的是在close的时候,没有对fblog进行判断,则[close(fblog);]相当于[close(0);],也就是将STDIN关闭了。
此时,后面又出现了系统调用open,这个open的return code极其有可能就是0(因为STDIN被关闭后,0便可被其他的file descriptor重用)。如果一旦是0,if clause将为真,系统便会因为一个假的error退出。
In a word, 上述代码片段的错误共有三处:
1)作为file descriptor的int一定要初始化为-1
2)open的返回值判断以-1为错误(man open上也是这么说的,0的判断是一种投机的做法)
3)close(fd)的时候要判断>-1。防止非法内存访问。
阅读(2613) | 评论(0) | 转发(0) |