fd从python复制到子进程

时间:2022-02-21 16:21:51

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)

我认为我有一个ttyUSB设备的问题,因为从不同的进程同时有2个打开的ttyUSB fd。它是这样的:我有一个主要的python进程,打开几个ttyUSB fd,读取,写入,关闭和打开进程(使用popen)来处理每个ttyUSB(当然在fd关闭后)。当我做'lsof | grep ttyUSB'看起来好像在子进程启动时在主进程中打开的所有fd都与子进程相关联,即使它们已经被主进程关闭了。 (顺便说一句,fd与主进程无关)

is that behavior normal? (tinycore, kernal 2.6.33.3), do i have a way to prevent it?

那种行为正常吗? (tinycore,kernal 2.6.33.3),我有办法预防吗?

thanks.

1 个解决方案

#1


0  

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 using fcntl(fd, F_SETFD, FD_CLOEXEC). (This makes the kernel automatically close the file descriptor when it execs the new process.)

默认情况下,进程在forks / execs(在popen()期间发生)时打开的任何文件描述符都由子进程继承。如果这不是您想要发生的,您将需要在分叉后手动关闭文件描述符,或者使用fcntl(fd,F_SETFD,FD_CLOEXEC)将fds设置为close-on-exec。 (这使得内核在执行新进程时会自动关闭文件描述符。)

#1


0  

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 using fcntl(fd, F_SETFD, FD_CLOEXEC). (This makes the kernel automatically close the file descriptor when it execs the new process.)

默认情况下,进程在forks / execs(在popen()期间发生)时打开的任何文件描述符都由子进程继承。如果这不是您想要发生的,您将需要在分叉后手动关闭文件描述符,或者使用fcntl(fd,F_SETFD,FD_CLOEXEC)将fds设置为close-on-exec。 (这使得内核在执行新进程时会自动关闭文件描述符。)