开发者

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

开发者 https://www.devze.com 2023-03-15 23:47 出处:网络
I\'m using fork(). However, before executing fork(), I open a file (say a.txt开发者_开发百科) using freopenfor writing. Now the child process redirects the output of execlp to a.txt. After terminating

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

精彩评论

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

关注公众号