fork后,我们会调用exec执行另一个程序,此时会用全新的程序替换子进程的正文,数据,堆和栈,那这样的话子进程的文件描述符表所占的内存也自动释放了吧,为什么还会存在是否要关闭子进程的文件描述符一说?
难道不关闭子进程的文件描述符,exec新的程序还能使用?新的程序好比是一个新的进程,而文件描述符是进程之间独立的,所以这不合乎逻辑啊?求大神解惑
阿神2017-04-17 15:37:26
Yes, the file descriptor of the child process has indeed been released, but the biggest reason for closing the file descriptor is because of the existence of the buffering mechanism. If it is not closed, incomplete data will be written. Of course, there are other reasons. After the exec function, it can be considered a new process. Everything is new except the process identifier. The file descriptor is maintained by the process, but the process descriptor is just a pointer-like thing. What it really points to is maintained by the kernel. In the file table, only the file descriptors are recycled. If the file table entries are not recycled, it is the same as a memory leak.
PHPz2017-04-17 15:37:26
Please refer to close_on_exec
As you said, if the child process does not close the file descriptor, it can still be used after exec, such as 0, 1, 2