【发布时间】:2012-06-20 20:48:44
【问题描述】:
我想从 IDE 调试我的 cgi 脚本 (C++),所以我想创建一个“调试模式”:从磁盘读取文件,将其推送到自己的标准输入,设置一些与此文件相对应的环境变量并运行Web 服务器调用的脚本的其余部分。是否有可能,如果是,那我该怎么做?
【问题讨论】:
我想从 IDE 调试我的 cgi 脚本 (C++),所以我想创建一个“调试模式”:从磁盘读取文件,将其推送到自己的标准输入,设置一些与此文件相对应的环境变量并运行Web 服务器调用的脚本的其余部分。是否有可能,如果是,那我该怎么做?
【问题讨论】:
您不能“推送到自己的标准输入”,但您可以将文件重定向到您自己的标准输入。
freopen("myfile.txt","r",stdin);
【讨论】:
fungetc 只工作 1 个字节。它不能按预期用于 cgi 输入。
每个人都知道标准输入是定义为STDIN_FILENO 的文件描述符。虽然它的值不能保证是0,但我从未见过其他任何东西。无论如何,没有什么可以阻止您写入该文件描述符。举个例子,这是一个小程序,它向自己的标准输入写入 10 条消息:
#include <unistd.h>
#include <string>
#include <sstream>
#include <iostream>
#include <thread>
int main()
{
std::thread mess_with_stdin([] () {
for (int i = 0; i < 10; ++i) {
std::stringstream msg;
msg << "Self-message #" << i
<< ": Hello! How do you like that!?\n";
auto s = msg.str();
write(STDIN_FILENO, s.c_str(), s.size());
usleep(1000);
}
});
std::string str;
while (getline(std::cin, str))
std::cout << "String: " << str << std::endl;
mess_with_stdin.join();
}
保存到test.cpp,编译运行:
$ g++ -std=c++0x -Wall -o test ./test.cpp -lpthread
$ ./test
Self-message #0: Hello! How do you like that!?
Self-message #1: Hello! How do you like that!?
Self-message #2: Hello! How do you like that!?
Self-message #3: Hello! How do you like that!?
Self-message #4: Hello! How do you like that!?
Self-message #5: Hello! How do you like that!?
Self-message #6: Hello! How do you like that!?
Self-message #7: Hello! How do you like that!?
Self-message #8: Hello! How do you like that!?
Self-message #9: Hello! How do you like that!?
hello?
String: hello?
$
“你好?”部分是我在发送完所有 10 条消息后键入的内容。然后按 Ctrl+D 表示输入结束,程序退出。
【讨论】:
stdin,std::cin 等呢?让我想起一部电影,其中机器人不断说“需要更多输入”>;-))