【问题标题】:Linux C++ run and communicate with new processLinux C++ 运行并与新进程通信
【发布时间】:2010-11-08 20:04:44
【问题描述】:

我需要制作一个程序来运行一个进程(我的另一个程序)并且可以与这个进程通信(发送标准输入和接收标准输出)。 我已经阅读了诸如 popen()CreateProcess() 之类的函数,但我并不真正了解如何使用它们。

如果你给我看一些示例代码(如何启动进程、发送标准输入、接收标准输出),那就太好了。 首选 C++ 函数(如果有的话)。

谢谢你的建议。

【问题讨论】:

    标签: c++ linux unix


    【解决方案1】:

    POSIX 函数的接口仅限 C 语言。但是你可以在 C++ 中使用它们。

    基本上:

    #include <unistd.h>
    // Include some other things I forgot. See manpages.
    
    int main()
    {
        // Open two pipes for communication
        // The descriptors will be available to both
        // parent and child.
        int in_fd[2];
        int out_fd[2];
    
        pipe(in_fd);  // For child's stdin
        pipe(out_fd); // For child's stdout
    
        // Fork
        pid_t pid = fork();
    
        if (pid == 0)
        {
            // We're in the child
            close(out_fd[0]);
            dup2(out_fd[1], STDOUT_FILENO);
            close(out_fd[1]);
    
            close(in_fd[1]);
            dup2(in_fd[0], STDIN_FILENO);
            close(in_fd[0]);
    
            // Now, launch your child whichever way you want
            // see eg. man 2 exec for this.
    
            _exit(0); // If you must exit manually, use _exit, not exit.
                      // If you use exec, I think you don't have to. Check manpages.
        }
    
        else if (pid == -1)
            ; // Handle the error with fork
    
        else
        {
            // You're in the parent
            close(out_fd[1]);
            close(in_fd[0]);
    
            // Now you can read child's stdout with out_fd[0]
            // and write to its stdin with in_fd[1].
            // See man 2 read and man 2 write.
    
            // ...
    
            // Wait for the child to terminate (or it becomes a zombie)
            int status
            waitpid(pid, &status, 0);
    
            // see man waitpid for what to do with status
        } 
    }
    

    不要忘记检查错误代码(我没有),并参考手册页了解详细信息。但是您明白了这一点:当您打开文件描述符时(例如,通过pipe),它们将可供父母和孩子使用。父关闭一端,子关闭另一端(并重定向第一端)。

    要聪明,不要害怕谷歌和手册页。

    【讨论】:

      猜你喜欢
      • 2012-10-20
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多