Hi Jim,
in comp.unix.solaris:
It's a bug.Quote:> We have run into an interesting problem under Solaris 2.5.1 using
> the dup2() system call.
>[...]
> new_socket_num = accept(old_socket_num,....)
> read(new_socket_num,...)
> fork(....)
> *** CHILD ***
> close(old_socket_num)
> close(0)
> close(1)
> close(2)
> dup2(new_socket_num,0)
> dup2(new_socket_num,1)
> dup2(new_socket_num,2)
> ...
> execl(...)
> *** PARENT ***
> close(new_socket_num)
> The FIRST dup2() will fail, with an errno of EBADF (not a valid
> open file descriptor). How is this error message possible since we
> successfully performed a read() from the socket descriptor? We
> have restarted the process as well as rebooted the machine to no avail.
Most likely the program, being a daemon, has closed standard input, output
and error, file descriptors 0, 1 and 2, early on. The fd returned by
accept is most likely 0, 1 or 2, which gets closed in your sequence of
three close()s. It's unnecessary to close a fd before using it as the
target fd in dup2(). So the only thing that remains is to close
new_socket_num, provided it is not 0-2, before the execl(); this is just
to be tidy.
So, the fixed code looks like:
new_socket_num = accept(old_socket_num, ...)
read(new_socket_num, ...)
fork(...)
*** CHILD ***
close(old_socket_num)
dup2(new_socket_num, 0)
dup2(new_socket_num, 1)
dup2(new_socket_num, 2)
if (new_socket_num > 2)
close(new_socket_num)
...
execl(...)
*** PARENT ***
close(new_socket_num)
HTH,
Sean.
--
Systems Programmer Information Services Griffith University