问题
I want to debug my cgi script (C++) from IDE, so I would like to create a "debug mode": read file from disk, push it to own stdin, set some environment variables, that correspond this file and run the rest of the script as it was called by the web server. Is it possible and if it is, then how can I do that?
回答1:
You can't "push to own stdin", but you can redirect a file to your own stdin.
freopen("myfile.txt","r",stdin);
回答2:
Everybody knows that standard input is a file descriptor defined as STDIN_FILENO
. Though its value is not guaranteed to be 0
, I never saw anything else. Anyway, there is nothing that prevents you from writing to that file descriptor. For the sake of example, here is a small program that write 10 messages to its own standard input:
#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();
}
Save that into test.cpp
, compile and run:
$ 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?
$
The "hello?" part is something that I typed after all 10 messages were sent. Then you press Ctrl+D to indicate end of input and program exits.
来源:https://stackoverflow.com/questions/11127970/is-it-possible-to-write-data-into-own-stdin-in-linux