Reputation: 19482
This might be a basic question. How to close a fd safely?
I am thinking like this.
void safe_close(int *fd) {
if (*fd >= 0) {
close(*fd);
*fd = -1;
}
return;
}
Upvotes: 0
Views: 193
Reputation: 714
The question is sort of basic but very important, and your solution looks mostly good to me. One thing to note though is that your fd is being passed by value, so the change to value -1 will not be reflected in the calling method. Also, according to the Linux man pages on close(), it is important to check the return value of close(). It says that it is "quite possible that errors on a previous write() operation are first reported at the final close()." Your method should probably at least print a message if an error occurred during the close, so that any loss of data can be traced.
Upvotes: 1