Thread communication via printf and scanf (linux)

南笙酒味 提交于 2019-12-24 09:15:40

问题


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 must 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).


回答1:


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.



来源:https://stackoverflow.com/questions/6527601/thread-communication-via-printf-and-scanf-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!