生成一个新终端并写入其标准输出 [英] spawning a new terminal and writing to its stdout

查看:31
本文介绍了生成一个新终端并写入其标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,它使用 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

}

推荐答案

  1. 打开管道.
  2. 叉子.
  3. 在子进程中,关闭写端并exec到一个运行cat/dev/fd/xterm.
  4. 在父进程中,关闭读端,写到写端.

#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;
}

您可以使用 fdopenfds[1] 转换为您可以使用 fprintfFILE *诸如此类.

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

这篇关于生成一个新终端并写入其标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆