开发者

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜