Back to Operating Systems Home Page
Next: Forkingduping, piping, waiting
Up: 1997 term messages
Previous: 8 deadly sins
> I understand how fork() and exec() work, but I'm not sure if
> exec() inherits the following: (I know that fork does)
>
> 1. Any 'duped' file descriptors.
> 2. The files that are open remain open.
> 3. If the standard output is duplicated in a file
> descriptor, is it the same for the program after exec()
These are all properties of the process, regardless of the
program running in it. Exec simply replaces the program inside
the process.
> 4. Any unflushed buffers
I assume you mean stdio buffers, i.e. buffers of FILEs managed by the
stdio C library. The answer is no, since the FILEs themselves are program
variables (the library being linked to the program at compile time). All
program memory is overwritten upon entering and exec(2) call. However,
data which have already been moved from stdio buffers to kernel
structures (e.g. to pipe buffers, or to the disk buffer cache) are not
lost.
Take-home lesson: if you want to use stdio routines "across" a
fork-exec pair, either:
(1) don't, and use directly the system calls (read(2), write(2))
(2) do, but fflush(3) the buffers before exec'ing
(3) do, but unbuffer the FILEs by calling setbuf(3) immediately
after fopen'ing or fdopen'ing them, and *before* performing
any other stdio operation on them.
(3) is a safer solution than (2).
> I know that read will return a 0 at the EOF, but it also
> returns the number of bytes read.
> What if we have an input of 50 characters, say, and the EOF
> is encountered after; which value does it return in this
> case?
There's some confusion in the above paragraph. Under UNIX no EOF
"character" needs be encountered "after", since no EOF is needed in the
file to mark its end. EOF is not even an ASCII character, but just a
manifest constant (-1) #defined in header stdio.h. The kernel, as I said
in class, keeps track of the file length in kernel-only data
structures (the v-node table), not inside the file.
However some stdio library use that constant to tell the calling program
that no further data are available from a stream. In particolar fgetc(3),
getc(3) and getchar(3) return EOF in this case (and that's why they are
declared as returning int and not char).
\
Franco Callari