Linux C ++运行并与新进程通信 [英] Linux C++ run and communicate with new process

查看:87
本文介绍了Linux C ++运行并与新进程通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要制作一个运行一个进程的程序(我的另一个程序),并且可以与此进程进行通信(发送stdin和接收stdout). 我已经阅读过有关popen()CreateProcess()之类的功能的信息,但我不太了解如何使用它们.

I need to make a program that runs a process (my another programm) and can communicate with this process (sending stdin and recieving stdout). I have read about functions like popen() and CreateProcess() but I don't really understand how to work with them.

如果您给我看一些示例代码(如何启动过程,发送stdin,接收stdout),那将是很棒的. 最好使用C ++函数(如果有的话).

Would be great, if you show me some sample code (how to start process, send stdin, recieve stdout). C++ functions would be preferred (if there are any).

谢谢你的建议.

推荐答案

POSIX的接口仅使用C语言.但是您可以在C ++中使用它们.

The interface for POSIX functions C language only. But you can use them in 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),父级和子级都可以使用它们.父母封闭一端,孩子封闭另一端(并重定向第一端).

Don't forget to check error codes (which I did not), and refer to man pages for details. But you see the point: when you open file descriptors (eg. via pipe), they will be available to parent and child. The parent closes one end, the child closes one other end (and redirects the first end).

要聪明,不要害怕Google和手册页.

Be smart and not afraid of google and man pages.

这篇关于Linux C ++运行并与新进程通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆