如何打开多个终端并行执行不同任务?

操作系统:Ubuntu
编程语言:C++
我想知道如何在同一段C++代码中通过for循环打开多个终端,每个终端执行自己的任务?这个代码应该怎么写?

博主可以使用C++的std::system函数来实现:

#include <iostream>
#include <string>
#include <stdlib.h>

int main() {
    for (int i = 0; i < 5; i++) {
        std::string command = "gnome-terminal -e 'bash -c \"echo Task " + std::to_string(i) + "; exec bash\"'";
        std::system(command.c_str());
    }
}

上面这段代码将会在5个终端中分别显示“Task 0”,“Task 1”,“Task 2”,“Task 3”和“Task 4”。

chatgpt:

#include <cstdlib>
#include <cstdio>
#include <iostream>

using namespace std;

int main() {
    for (int i = 0; i < 3; i++) {
        char command[100];
        sprintf(command, "gnome-terminal -- sh -c 'echo \"Task %d\"; exec bash'", i+1);
        system(command);
    }
    return 0;
}

在这个程序中,使用sprintf函数将要执行的命令以字符串形式存储在command数组中,然后使用system函数执行该命令。在这个命令中,使用echo命令打印出一个字符串,并使用exec bash命令启动一个新的Bash shell来保持终端窗口的打开状态。