iFederx
iFederx

Reputation: 864

Closing a file descriptor (or a socket) in C

I have a doubt: when I create a file descriptor with an fd = open() or a socket with a fd = socket(), and I pass it in a function function(fd) that does close(fd), in the main function, fd is still available or doesn't it work? In other words, when I close a file descriptor passed to a function by value, is it closed also for the calling function?

Upvotes: 1

Views: 13357

Answers (2)

Yes, a file descriptor (on Unix systems, POSIX ones, ...) is known to the kernel and to your entire current process. Each process has its own file descriptor table and virtual address space.

On Linux, you can use proc(5) to query both the file descriptors and the virtual address space of some process. For the process of pid 1234, use /proc/1234/fd/ & /proc/1234/fdinfo/ to understand its file descriptors and their table, and /proc/1234/maps & /proc/1234/smaps to understand its virtual address space.

So if a called function close-s it, you should not use it anymore. Of course, you might reactivate it (with some other open, socket, dup returning it).

Therefore, you need to define, document and explicit conventions about close-ing responsibilities (like you do about free-ing pointers). Read also about RAII.

In that aspect, close is a bit like free: it is invalidating the value (file descriptor for close, pointer for free) passed to it. When possible, you could set the file descriptor to -1 (or some other invalid value) after a successful close(2), so code close(fd); fd = -1; for example. For similar reasons, I also do free(ptr), ptr = NULL; when possible.

BTW, I'm supposing a Unix or POSIX (or Linux) system. I don't know Windows, and it has a very different notion of file descriptors and of sockets.

Upvotes: 7

Greg Gardner
Greg Gardner

Reputation: 190

I suggest you read some documentation on the close() system call, but yes calling close() regardless of 'where' in process, will cause a trap into the kernel and remove access to the fd for the process. It will not necessarily free up any assets.

Upvotes: 1

Related Questions