簡體   English   中英

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

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

我正在嘗試從Linux C ++程序中執行外部程序。

我正在調用方法system("gedit")來啟動Gedit編輯器的實例。 但是我的問題是當Gedit窗口打開時,我的C ++程序等待它退出。

如何在不等待退出的情況下調用外部程序?

你需要使用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
}

您還需要收獲您的孩子,以免留下僵屍進程。

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

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

關於僵屍進程,您有第二種選擇。 它使用了更多的資源(這種味道分叉兩次),但好處是你可以讓你的等待更接近你的叉子,這在維護方面更好。

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
}

這最后一種風格的作用是創造一個孩子,這反過來創造了一個孫子,而孫子就是exec的你的gedit程序。 孩子本身退出,父進程可以立即收獲。 所以一個額外的分叉,但你把所有的代碼保存在一個地方。

哦,讓我說吧!

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

叉子! :)

首先,你是否嘗試在system("gedit&")背景下啟動system("gedit&")

如果這不起作用,請嘗試生成一個新線程並從那里運行gedit。

我假設您不關心編輯結果或編輯文件的內容?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM