Search code examples
clinuxgnome-terminal

Open 2 terminals using system() and select default for output


I have a simple program like this

int main(void) {

    system("gnome-terminal");
    puts("terminal 1");
    system("gnome-terminal");
    puts("terminal 2");

    return EXIT_SUCCESS;
}

At runtime: Opens only the first terminal and only when I close it the program continues, prints in the console and opens the second.

How can I open both of them? (without stopping my program's execution when the first is open)

How can I selectively print in the two terminals inside of my program? (puts("something"); at second terminal)

Thanks


Solution

  • That is not possible because system blocks until the executed program ends, one possible solution is to use fork()

    #include <stdio.h>
    #include <unistd.h>
    
    int main(void) 
    {
        int i;
    
        for (i = 0 ; i < 2 ; ++i)
        {
            if (fork() == 0)
            {
                printf("terminal %d\n", 1 + i);
                system("gnome-terminal");
            }
        }
        return EXIT_SUCCESS;
    }
    

    if you want to comunicate with the executed program, read popen(). And you might also be interested in execv() and family.