spawning a new terminal and writing to its stdout

北城余情 提交于 2021-02-08 18:41:05

问题


I have an application that uses a gui to do most of its interface with the user. However I would like to have a separate terminal window that I can write to for some error checking, raw values etc.

I know I can spawn a new terminal with the system() command but I have no idea if interaction is possible.

in the best possible scenario I would like to have a function which takes a string(char array I know...), and prints it to the newly spawned console window:

something like:

int func(char *msg) {
    static // initiate some static interface with a newly spawned terminal window.

    // check if interface is still valid

    // send data to terminal

    return 0; //succes

}

回答1:


  1. Open a pipe.
  2. Fork.
  3. In the child process, close the write end and exec to an xterm running cat /dev/fd/<rdfd>.
  4. In the parent process, close the read end and write to the write end.
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>

int main(int argc, char **argv) {
    (void)argc, (void)argv;

    int fds[2];
    if(pipe(fds) == -1) {
        abort();
    }

    int child_pid = fork();
    if(child_pid == -1) {
        abort();
    }

    if(child_pid == 0) {
        close(fds[1]);
        char f[PATH_MAX + 1];
        sprintf(f, "/dev/fd/%d", fds[0]);
        execlp("xterm", "xterm", "-e", "cat", f, NULL);
        abort();
    }

    close(fds[0]);
    write(fds[1], "Hi there!\n", sizeof("Hi there!\n"));
    sleep(10);
    close(fds[1]);
    sleep(3);

    return EXIT_SUCCESS;
}

You can use fdopen to turn fds[1] into a FILE * that you can use fprintf and such on.




回答2:


Well, imagine a scenario where the terminal is your main output device (e.g. tty[n]), how would one open a "new" terminal then?

The only reason you can open multiple terminals in a graphical DE is because they are terminal emulators. You would need to launch another terminal emulator and write to the standard output of that using something like a socket or maybe shared memory.



来源:https://stackoverflow.com/questions/24522680/spawning-a-new-terminal-and-writing-to-its-stdout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!