I'm using fork()
. However, before executing fork()
, I open a file (say a.txt
) using freopen
for writing. Now the child process redirects the output of execlp
to a.txt
. After terminating the child process, the parent process closes a.txt
. Now how can the parent process read a.txt
and show some information in stdout
?
Asked
Active
Viewed 734 times
0

miraj
- 493
- 2
- 6
- 7
2 Answers
1
If the parent process opened the file with freopen(3)
, then the rewind(3)
library call can be used to re-wind the stream's pointer to the start of the file, for use with fread(3)
or fgets(3)
or whatever API you'd like to use.

sarnold
- 102,305
- 22
- 181
- 238
-
@ sarnold: But I can't write to `stdout`. – miraj Jun 27 '11 at 23:29
-
@miraj, aha; I think R.. understood your problem better than I did. Is your trouble writing to the file in the child? Or is the problem reading from the file in the parent? – sarnold Jun 28 '11 at 00:02
-
The child can write perfectly. The problem is in reading the file and writing to stdout by the parent. – miraj Jun 28 '11 at 00:41
1
freopen
does not belong in this code at all. Instead, you should do something like:
FILE *tmp = tmpfile();
if (!(pid=fork())) {
dup2(fileno(tmp), 1);
close(fileno(tmp));
execlp(...);
_exit(1);
}
wait(&status);
/* read from tmp */
However it would actually be a lot better to use a pipe if possible.

R.. GitHub STOP HELPING ICE
- 208,859
- 35
- 376
- 711