为什么这个程序(有时)会失败?
#include <cstdio>
#include <QtCore/QProcess>
int main (int argc, char** argv) {
// if we remove 3 following lines, the problem described below doesn't exists!!
QProcess process;
process.start ("asdqwe"); // doesn't matter what we try to execute here.
process.waitForStarted (1000);
while (true) {
char buf[100];
if (scanf ("%s", buf) == EOF) { // it looks like stdin is closed!
printf("FAIL\n");
return 1;
}
printf ("%s\n", buf);
}
return 0;
}
这段代码只是显示问题的一个片段。在完整的应用程序中,我需要与进程进行读/写通信。
我用以下命令编译它:
g++ -o out ./main.cpp -I /usr/include/qt4/ -lQtCore
并从终端中的 bash 命令行执行它。
为什么这个程序有时会打印 FAIL,有时会停留在循环中?
编辑: 这不是关于 scan/printf 的问题。 如果我使用 iostreams + string,也会出现同样的问题。这个问题是关于 QProcess 与父进程的文件描述符的交互。
#include <cstdio>
#include <QtCore/QProcess>
int main (int argc, char** argv) {
// if we remove 3 following lines, the problem described below doesn't exists!!
QProcess process;
process.start ("asdqwe"); // doesn't matter what we try to execute here.
process.waitForStarted (1000);
while (true) {
char buf[100];
if (scanf ("%s", buf) == EOF) { // it looks like stdin is closed!
printf("FAIL\n");
return 1;
}
printf ("%s\n", buf);
}
return 0;
}
This code is just a snippet to show the problem. In the full application I need read/write communication with process.
I compile it with:
g++ -o out ./main.cpp -I /usr/include/qt4/ -lQtCore
And execute it from bash command line in terminal.
Why this program sometimes prints FAIL and sometimes will stay in loop?
Edit:
This is not question about scan/printf.
The same problem is if I use iostreams + string. This question is about interaction of QProcess with file descriptors of parent process.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
scanf
被子进程终止时捕获的 SIGCHLD 信号中断。在这种情况下,还会返回 EOF。QProcess
stuff 确实为 SIGCHLD 设置了信号处理程序(检查源):(此处为 4.5.3)Your
scanf
was interrupted by SIGCHLD signal that was caught when child process terminated. In this caseEOF
is also returned.QProcess
stuff does set up signal handler for SIGCHLD (check sources): (4.5.3 here)我真的使用流,我必须使用
I really use streams, I had to use