1

我正在编写一个 c++ 应用程序(在 Linux 中),我想在其中启动另一个应用程序,只有一次。(如果它已经打开,而不是使用handle那个)。

有时我也想为相同的应用程序提供输入。例如:

    class myapp():
        start second application here.
        work()
    myapp::work(){
        create input
        provide input to the started/already open second application
    }

因此,每次为 myapp 创建对象时,都会启动第二个应用程序(仅当它尚未打开时)。然后每次将输入传递给应用程序?那可能吗?我也不希望第二个应用程序关闭,除非用户结束它。我已经在使用 pid 和 fork 来做到这一点。但不知何故,它多次启动应用程序,我都无法为这个应用程序提供输入。

希望这足够清楚。我知道已经有很多关于此的问答,但我无法清楚地理解,因此如果我再次问同样的问题,请道歉?

谢谢您的帮助

4

1 回答 1

2

popen is the right tool for this job. You pass it a command to execute, and it return you receive a C file handle (FILE *) which represents the pipe from your program to the second one. All data you write with this handle is directed to the second program's standard input.

Note that this is a C file handle, so you'll need to use C I/O functions such as fprintf to write to it. Unfortunately, there is no standard way of converting a C file handle to a C++ output stream.

Here is an example of how you might use popen, adapted from the example in the GNU libc manual:

FILE *pipe = popen("wireshark -i -k", "w"); // "w" means "write mode"
if (!pipe) {
    // execution failed
    return;
}

fprintf(pipe, "Some data");
…

// When you're done with the pipe:
pclose(pipe);

You can make sure that the program is started only once by storing the pipe FILE * in a permanent variable (e.g. an object member variable) that you initialize with NULL. Then you can easily check if you have already started the second application with pipe != NULL.

于 2013-07-29T05:39:48.570 回答