【问题标题】:Is it possible to write data into own stdin in Linux是否可以在 Linux 中将数据写入自己的标准输入
【发布时间】:2012-06-20 20:48:44
【问题描述】:

我想从 IDE 调试我的 cgi 脚本 (C++),所以我想创建一个“调试模式”:从磁盘读取文件,将其推送到自己的标准输入,设置一些与此文件相对应的环境变量并运行Web 服务器调用的脚本的其余部分。是否有可能,如果是,那我该怎么做?

【问题讨论】:

    标签: c++ linux cgi


    【解决方案1】:

    您不能“推送到自己的标准输入”,但您可以将文件重定向到您自己的标准输入。

    freopen("myfile.txt","r",stdin);
    

    【讨论】:

    • 好吧,假设 stdio,有fungetc。但这并不能保证超过一个字节的回推。
    • 好吧。 fungetc 只工作 1 个字节。它不能按预期用于 cgi 输入。
    【解决方案2】:

    每个人都知道标准输入是定义为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 表示输入结束,程序退出。

    【讨论】:

    • 这看起来有点工作,因为你在一个终端,文件描述符 0、1 和 2 都与 pty 绑定。你没有写任何程序本身可以读回的东西。有关此主题的一些说明,请参阅stackoverflow.com/q/1441251
    • 是的。如果您与 tty 分离,您的输入 fd 也可以关闭。我想一个确切的解决方案取决于上下文。很有可能做 pipe/dup2 等。如果你重新打开stdinstd::cin 等呢?让我想起一部电影,其中机器人不断说“需要更多输入”>;-))
    • 这不能按预期工作。看看所有的自我信息行是如何不以“字符串:”开头的。如果它实际上通过了 main 中的 while 循环,应该就是这种情况。
    猜你喜欢
    • 2016-06-13
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    相关资源
    最近更新 更多