fd 从 python 到子进程的重复
我认为我的 ttyUSB 设备有问题,这是由于不同进程同时打开 2 个 ttyUSB fd 造成的。 它是这样的:
我有一个主要的python进程,它打开几个ttyUSB fd,读取、写入、关闭和打开进程(使用popen)来处理每个ttyUSB(当然是在fd关闭之后)。
当我做'lsof | grep ttyUSB' 看起来好像子进程启动时在主进程中打开的所有 fd 都与子进程关联,即使它们已经被主进程关闭。 (顺便说一句,文件描述符与主进程无关)
这种行为正常吗? (tinycore,kernal 2.6.33.3),我有办法阻止它吗?
谢谢。
i think i have a problem with a ttyUSB device that caused from having 2 open ttyUSB fd's at the same time from different processes.
it goes like this:
i have a main python process, which opens several ttyUSB fd's, read, write, close, and open processes (with popen) to handle each ttyUSB (of course after the fd was closed).
when i do 'lsof | grep ttyUSB' it looks as if all the fd's that were opened in the main process when the child process started, associated to the child process even though they were already closed by the main process. (btw, the fd's are not associated to the main process)
is that behavior normal? (tinycore, kernal 2.6.33.3), do i have a way to prevent it?
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,进程在 forks/execs(在
popen()
期间发生)时打开的任何文件描述符都由子进程继承。如果这不是您希望发生的情况,则需要在分叉后手动关闭文件描述符,或者使用 fcntl(fd, F_SETFD, FD_CLOEXEC) 将 fd 设置为 close-on-exec 。 (这使得内核在执行新进程时自动关闭文件描述符。)By default, any file descriptors that a process has open when it forks/execs (which happens during a
popen()
) are inherited by the child process. If this isn't what you want to happen, you will need to either manually close the file descriptors after forking, or set the fds as close-on-exec usingfcntl(fd, F_SETFD, FD_CLOEXEC)
. (This makes the kernel automatically close the file descriptor when it execs the new process.)