问题
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:
- Open a pipe.
- Fork.
- In the child process, close the write end and
exec
to anxterm
runningcat /dev/fd/<rdfd>
. - 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