01-25-07 12:19 AM
# I am implementing a PERL module which starts and maintains a new
# process. I use fork/exec on unix system. Somebody suggests me to use
# "system" instead of "fork/exec" and he thinks fork/exec are dangerous
# because of the handle inheritance might cause deadlock or lock
# conflicts on complicated systems. I still think fork/exec is safe
If a child inherits the read end of a pipe, the pipe
remains open until _all_ readsers close the pipe, whether
a process knows it's a reader or not.
Lock inheritance depends on the kind of lock.
Whether a process knows about open descriptors or not, simply
having them can affect other processes.
# enough, because except for STDIN, STDERR and STDOUT, child has no way
# to know the opened handles without passing parameters from parent. Also
# even if there is such possibility(eg. child uses 3 as a fd directly),
# can this be avoided by using "system"? I think "system" is implemented
# by "fork/exec".
Note also that stdin etc have nothing to do with the kernel or
fork/exec. These file descriptors are a shell convention only;
there's no reason you cannot establish a different or extended
process interface among your own programs.
# My questions are:
# 1. Is "system" implemented by "fork/exec/wait"? If so, does it have
# anything special to avoid the problems that might be caused by
# inheriting handles from the parent?
The only way to get a new process is fork or its variants.
The way to get a new VM image for a process is an exec variant.
The way to get child status is a wait variant. So, system, popen,
and anything else ultimately depends on this.
You can safely close unused descriptors. If you know the maximum
descriptor, you can do something like
for (fd=3; i<=maxfd; fd++) close(fd);
Undefined descriptors return an error on close that can be safely
ignored. You can also set close-on-exec on files with fcntl.
Note that FILE* exists only in your VM, so that an exec discards
the FILE and its buffers; the file descriptor the FILE is on
has to be dealt with as above.
# # 2. Is there a good way to get the pid of the new process if I use
# "system". I need to use this pid to maintain the new process.
system() does a fork/exec of your shell and passes the string in the
system() call to the shell; system() does not return until the shell
exits, so even if you know the pid, it's already gone. If the shell
command has unexitted grandchildren, (such system("tail -f logfile &")),
those are orphanned and belong to init. There's no general
mechanism for tracking orphanned processes from system() or any
other fmaily history.
#
# Thank you very much!
# -Connie
#
#
#
--
SM Ryan http://www.rawbw.com/~wyrmwif/
You face forward, or you face the possibility of shock and damage.
[ Post a follow-up to this message ]
|