开发者

Thread communication via printf and scanf (linux)

Working in Linux and using C++. I have a program which initiates a thread. I need the main thread and the child thread to communicate via printf and scanf (the code for both threads uses scanf and printf and assumes that it communicates with stdin and stdout. I m开发者_如何学运维ust keep it that way). I managed to override printf and scanf, so I have total control over these functions (and I can identify the calling thread using *pthread_self*).

What remains to be done is to create 2 file handles, one for each direction of the communication, and to buffer the communication. How can this be done?

Writing to a file on disk does not solve my problem as the communication may be very long and I can't afford to store it on disk. However, I do know that the reading thread will read the data not long after it's written, so not a lot of buffering is needed.

In particular, it is important that if one thread calls scanf("%s", &x) then it would be blocked until the other thread writes some string and adds whitespace (so the string is not read before it is completely written).


You can use pipes. http://linux.die.net/man/2/pipe . You can simply redirect stdout and stdin instead of overriding printf and scanf. Be careful though, as printf and scanf are not re-entrant.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜