使用close()关闭文件异常:传入无效FD却关闭最后打开文件
程序关闭文件时的异常问题
我的程序维护着一个已打开文件的列表,调用close()时并未关闭传入的文件描述符(FD),反而关闭了编号最大的文件。当传入超出范围的FD时,不会弹出perror错误提示,而是直接关闭最后打开的文件。
closeFd函数代码
bool closeFd(List *fileList, int position) { Pos p; p = findPosition(position, *listaFicheros); if (close(p->data.fileDescriptor) == (-1)) { perror("File non-existent"); return false; } else { deleteAtPosition(p, fileList); return true; } }
测试输出
> open try.txt cr Added entry 3 to the open files table -> open try2.txt tr Added entry 4 to the open files table -> open descriptor: 0 -> standard input descriptor: 1 -> standard output descriptor: 2 -> standard error descriptor: 3 -> try.txt O_CREAT descriptor: 4 -> try2.txt O_TRUNC -> close 8 -> open descriptor: 0 -> standard input descriptor: 1 -> standard output descriptor: 2 -> standard error descriptor: 3 -> try.txt O_CREAT -> close 6 -> open descriptor: 0 -> standard input descriptor: 1 -> standard output descriptor: 2 -> standard error -> close 9 -> open descriptor: 0 -> standard input descriptor: 1 -> standard output ->
注:close [fd]命令用于关闭对应文件描述符的文件,例如close 2应关闭标准错误;若为无效FD应弹出perror提示。但实际传入无效FD时,会关闭最后打开的文件。
辅助函数代码
findPosition函数
Pos findPosition(int position, List L) { Pos p; p = L; while (p->data.position != position && p->next != NULL) p = p->next; return p; }
deleteAtPosition函数
void deleteAtPosition(Pos p, List *L) { Pos q; if (p == *L) *L = (*L)->next; else if (p->next == NULL) { q = previous(p, *L); q->next = NULL; } else { q = p->next; p->data = q->data; p->next = q->next; p = q; } free(p); }
previous函数
Pos previous(Pos p, List L) { Pos q; if (p == L) return NULL; else { for (q = L; q->next != p; q = q->next) ; return q; } }
链表头文件代码
#define COMMAND_LENGTH 50 typedef char command[COMMAND_LENGTH]; typedef struct Item { command name; int fileDescriptor; int position; int mode; } Item; typedef struct Node *Pos; struct Node { Pos next; Item data; }; typedef Pos List;
内容的提问来源于stack exchange,提问作者jamondebellota
相关产品推荐
相关产品推荐

