dup()

Would anyone be so kind to explain to me the function of dup() in UNIX? As far as I am concerned, it duplicates a file descriptor. Under what circumstances would we need to duplicate a file descriptor in a UNIX environment?

Thank you.

vinchen

For example, think about inetd. It has dozens of fd's open. It gets a connection for telnet on one them. So it forks a child. The child must exec telnetd, but first that socket must be duped onto fd's 0 1 and 2.

And lots of times you want to open a file on fd 1 and dup it to fd 2. Opening the file twice would result in two file table entries and then fd 1 and fd 2 would be stepping on each other. Anytime you see "2>&1" in a shell script you're asking the shell to dup an fd.

Anyway, few people actually use dup() anymore. dup2() or fnctl() can dup an fd with more control over the target fd.

hi ..,

You are right, its used to duplicate the file discriptor.

the application demands the situation for example,

you have a client to pull data from a server on a different m/c and
you want your clients to run as daemon processes,
you can not associate any terminal device associated for daemon processes.
In this case, you open a null file discriptor with
open("/dev/null",O_RDONLY)
and dup this discriptor for stdin , stdout and stderr.
this prevents your processes from directly writing or reading from stdio.

I hope this might help you a bit in understanding.

thanks
reddyb

Thank you very much people.

:smiley: