【问题标题】:opening a C program in new terminal window在新的终端窗口中打开 C 程序
【发布时间】:2016-08-16 08:55:27
【问题描述】:
 gcc version 5.3.0 20151204 (Ubuntu 5.3.0-3ubuntu1~14.04) 

我阅读了this 并找到了这一行:

int exit_status = system("gnome-terminal");

所以当我将它添加到我的代码中时,它只会打开一个新的终端窗口(这就是他所要求的),但我的程序在旧窗口中运行。

有什么方法可以在新的终端窗口中运行我的程序。 而且当程序完成执行时,终端窗口会像我输入exit 命令一样关闭

【问题讨论】:

    标签: c linux ubuntu terminal system


    【解决方案1】:

    system("gnome-terminal"); 将运行给定的命令,等待它退出,然后继续执行您的程序。这就是您的程序继续在当前终端窗口中运行的原因。

    与尝试在 C 中执行此操作相比,为您的程序编写一个 shell 脚本包装器并使用该脚本在新的终端窗口中启动您的程序可能更有意义:

    #!/bin/bash
    
    gnome-terminal -e ./your-program-name your program arguments
    

    使脚本可执行 (chmod +x script-name),然后您可以像运行 C 程序一样运行它。您甚至可以让它将参数从脚本转发到您的实际程序:

    #!/bin/bash
    
    gnome-terminal -e ./your-program-name "$@"
    

    请注意,您可以使用更中性的x-terminal-emulator 命令,而不是使用gnome-terminal(假设用户安装了gnome)(参见How can I make a script that opens terminal windows and executes commands in them?)。


    如果您真的想从您的 C 程序中执行此操作,那么我建议您执行以下操作:

    #include <stdio.h>
    #include <stdlib.h>
    
    char cmd[1024];
    
    int main(int argc, char *argv[]){
        // re-launch in new window, if needed
        char *new_window_val = getenv("IN_NEW_WINDOW");
        const char *user_arg = argc < 2 ? "" : argv[1];
        if (!new_window_val || new_window_val[0] != '1') {
            snprintf(cmd, sizeof(cmd), "gnome-terminal -e IN_NEW_WINDOW=1 %s %s", argv[0], user_arg);
            printf("RELAUNCH! %s\n", cmd);
            return system(cmd);
        }
        // do normal stuff
        printf("User text: %s\n", argv[1]);
        return 0;
    }
    

    使用环境变量(在这种情况下为IN_NEW_WINDOW)来检查您是否已经在新窗口中启动应该使新窗口只打开一次。请注意,上面的代码假定程序只有一个参数。

    但是,我仍然认为使用包装脚本是更好的解决方案。

    【讨论】:

    • 是的,我发现使用外壳要好得多。谢谢!
    猜你喜欢
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 2013-08-12
    • 2013-11-18
    • 1970-01-01
    • 2017-04-10
    相关资源
    最近更新 更多