简体   繁体   English

如何在不等待退出的情况下运行外部程序?

[英]How can I run an external program without waiting for it to exit?

I'm trying to execute an external program from inside my Linux C++ program. 我正在尝试从Linux C ++程序中执行外部程序。

I'm calling the method system("gedit") to launch an instance of the Gedit editor. 我正在调用方法system("gedit")来启动Gedit编辑器的实例。 However my problem is while the Gedit window is open, my C++ program waits for it to exit. 但是我的问题是当Gedit窗口打开时,我的C ++程序等待它退出。

How can I call an external program without waiting for it to exit? 如何在不等待退出的情况下调用外部程序?

You will need to use fork and exec 你需要使用forkexec

int fork_rv = fork();
if (fork_rv == 0)
{
    // we're in the child
    execl("/path/to/gedit", "gedit", 0);

    // in case execl fails
    _exit(1);
}
else if (fork_rv == -1)
{
    // error could not fork
}

You will also need to reap your child so as not to leave a zombie process. 您还需要收获您的孩子,以免留下僵尸进程。

void reap_child(int sig)
{
    int status;
    waitpid(-1, &status, WNOHANG);
}

int main()
{
    signal(SIGCHLD, reap_child);
    ...
}

In regards to zombie processes, you have a second option. 关于僵尸进程,您有第二种选择。 It uses a bit more resources (this flavor forks twice), but the benefit is you can keep your wait closer to your fork which is nicer in terms of maintenance. 它使用了更多的资源(这种味道分叉两次),但好处是你可以让你的等待更接近你的叉子,这在维护方面更好。

int fork_rv = fork();
if (fork_rv == 0)
{
    fork_rv = fork();
    if (fork_rv == 0)
    {
        // we're in the child
        execl("/path/to/gedit", "gedit", 0);

         // if execl fails
        _exit(1);
    }
    else if (fork_rv == -1)
    {
        // fork fails
        _exit(2);
    }

    _exit(0);
}
else if (fork_rv != -1)
{
    // parent wait for the child (which will exit quickly)
    int status;
    waitpid(fork_rv, &status, 0);
}
else if (fork_rv == -1)
{
    // error could not fork
}

What this last flavor does is create a child, which in turns creates a grandchild and the grandchild is what exec's your gedit program. 这最后一种风格的作用是创造一个孩子,这反过来创造了一个孙子,而孙子就是exec的你的gedit程序。 The child itself exits and the parent process can reap it right away. 孩子本身退出,父进程可以立即收获。 So an extra fork but you keep all the code in one place. 所以一个额外的分叉,但你把所有的代码保存在一个地方。

Oh, let me say it! 哦,让我说吧!

http://en.wikipedia.org/wiki/Fork-exec http://en.wikipedia.org/wiki/Fork-exec

Fork! 叉子! :) :)

First, did you try to launch in background with system("gedit&") ? 首先,你是否尝试在system("gedit&")背景下启动system("gedit&")

If that does not work, try spawning a new thread and running gedit from there. 如果这不起作用,请尝试生成一个新线程并从那里运行gedit。

I presume that you are not concerned with the result of the edit, or the contents of the edited file? 我假设您不关心编辑结果或编辑文件的内容?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM