生成一个新终端并写入其标准输出 [英] spawning a new terminal and writing to its stdout
问题描述
我有一个应用程序,它使用 gui 来与用户进行大部分界面.但是,我想要一个单独的终端窗口,我可以写入该窗口以进行一些错误检查、原始值等.
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.
我知道我可以使用 system()
命令生成一个新终端,但我不知道是否可以进行交互.
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:
类似:
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
}
推荐答案
- 打开管道.
- 叉子.
- 在子进程中,关闭写端并
exec
到一个运行cat/dev/fd/
的xterm
. - 在父进程中,关闭读端,写到写端.
#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;
}
您可以使用 fdopen
将 fds[1]
转换为您可以使用 fprintf
的 FILE *
诸如此类.
You can use fdopen
to turn fds[1]
into a FILE *
that you can use fprintf
and such on.
这篇关于生成一个新终端并写入其标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!