问题
I am attempting to write a program which forks and waits for his child to finish, then the child does some work on an input and then forks the same way it's parent does and so on.
Now, I know that forking copies to the child the array of file descriptors and that I should close the ones associated with the parent, but I can't figure out which are the parents. Do I need to give to my child it's parents pid?
I've been trying to wrap my head around it for the better part of an hour and I think I have some kind of a mind block because I can't come to a conclusion.
TL;DR: As a child process how do I know which file descriptors belong to my parent?
回答1:
Just after the fork
(and before any exec
function) your child process has the same state as its parent process (except for the result of the fork
, which is 0 only in the child). So you know what are the file descriptors, since you have coded the program running in parent&child. On Linux you might also read the /proc/self/fd/
directory, see proc(5).
You might close most file descriptors after the fork
and before the exec
; you could code something like
for (int fd=3; fd<64; fd++) (void) close(fd);
we are starting from 3 which is after STDERR_FILENO
which is 2, and we are stopping arbitrarily at 64, and the cast to (void)
on the close
call means to the reader that we don't care about failing close
.... Of course, if you have e.g. some pipe(7)-s to communicate between parent and child you'll be careful to avoid closing their relevant file descriptor(s).
(However, doing a closing loop like above is poor taste and old fashion)
In general, you'll be careful in your program to set the close-on-exec flag on most file descriptors (e.g. fcntl(2) on F_SETFD
operation and FD_CLOEXEC
flag, or directly open(2) with O_CLOEXEC
), then the execve(2) (done in most child processes after the fork
) would close them.
来源:https://stackoverflow.com/questions/33722599/as-a-process-child-how-to-know-which-file-descriptor-is-parents