I'm writing an application in C++ for a linux environment which will operate in a multi-process setup (i.e. the program calls fork()). As part of the application I am creating some file descriptors (sockets in this case), I am wondering if it is possible for the program to determine how many other processes have that file descriptor open. In 开发者_开发技巧this case I want to perform special actions before closing the last copy of the file descriptor.
I know that the implementation of close for file descriptors like TCP sockets seem to accomplish this but I'm not sure how.
Edit: I'm looking for a way to accomplish this without access to the main or fork code. The code is in a library providing these sockets to other applications.
Example code:
void handle_socket(int socket_fd) {
// determine number of processes with this socket_fd open.
if (num_proc == 1) {
// Special code
}
close(socket_fd);
}
int main(int argc, char *argv[]) {
int socket_fd = socket(...);
if (fork() == 0) {
//action 1
} else {
// action 2
}
handle_socket(socket_fd);
return 0;
}
If you are writing the main() that spawns the child processes, you should be waiting for those children to finish.
精彩评论