[cs631apue] Last doubt for this class

Jan Schaumann jschauma at stevens.edu
Tue Dec 3 12:03:48 EST 2019


Siddharth Choudhary <schoud2 at stevens.edu> wrote:

> What happens if i try to reuse the file descriptor which is opened in the
> child?

I'm not sure I understand your question correctly; it
depends on what you mean by "reuse" as well as the
order of operations.

Suppose you have a process with an open file
descriptor that then forks.  As per slide 39 of
lecture 02
https://stevens.netmeister.org/631/lecture02.pdf
both processes now have their own handle with their
own offset.

If by "reuse" you mean "close the fd, open another
file, and happen to get back the same number", then
nothing surprising happens: it's a new file
descriptor, independent of the previous fd.

If you consider a process that forks and then opens a
file in each the parent and child, then each will have
their own, unique file descriptors.  The parent cannot
access the file descriptor in the child nor vice
versa.

If either process tries to guess the fd number of an
open file descriptor in the other process and tries to
access that, that would fail: each process has their
own set of file descriptors which are not shared, so
if e.g., the child opened a file and got back '4' as
the file descriptor, and the parent tried to write to
file descriptor '4', write(2) would return -1 with
errno set to EBADF.

I'm sorry, I'm not sure if this is what you were
asking.

> And what is the highest number of file descriptors which could be
> open in a particular process without affecting the child and parent process
> stack size?

The stack size and the number of file descriptors are
independent.  A file descriptor is a kernel resource,
which is limited as we discussed in lecture 02 by the
example of the ulimit.c program.

Try to write yourself a program that prints out how
many file descriptors it currently has in use, then
fork, print the same diagnostic, open/close some file
descriptors, print the same diagnostic etc.

-Jan


More information about the cs631apue mailing list