miraj
miraj

Reputation: 533

Want to write in stdout after closing the file opened using freopen

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?

Upvotes: 0

Views: 767

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215637

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.

Upvotes: 1

sarnold
sarnold

Reputation: 104110

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.

Upvotes: 1

Related Questions