c++ - 如何在C++中使用popen打开 "screen"?

标签 c++ linux macos popen gnu-screen

我有一个 C++ 程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <fcntl.h>
using namespace std;



int main (int argc, const char * argv[]) {
//    system("script /dev/null");
    FILE *pout;
    pout = popen("screen tty.MobileRobot-RNI-SPP", "w");
    fprintf(pout,"hello");


    return 0;
}

问题是它随后输出“必须连接到终端。”

命令然后挂起。取消注释 system() 调用不会导致任何事情发生。我不确定我是否做得正确。有任何想法吗?谢谢

最佳答案

您需要将子进程的 stdin 管道连接到实际终端...或者至少是伪终端。假设您使用的是 POSIX 系统(根据您的标签判断),您可以使用 posix_openptptsname得到这些。

伪代码(非线程安全):

const int flags = O_RDWR;
int pseudouser = posix_openpt(flags);
int pseudoprog = open(ptsname(pseudouser), flags);

if (fork()) {
    execv magic with pseudoprog;
    exit(0);
}

FILE *pout = fdopen(pseudouser, "r+");
do stuff with pout

有关 execv 的魔力,请参阅 this lovely blog post 。基本上,它做了一些魔法,使执行的进程使用某些文件描述符,然后主程序可以读取这些文件描述符。

或者,你可以做一些修改(仍然不是线程安全的):

const int flags = O_RDWR;
int pseudouser = posix_openpt(flags);
char *pseudoname = ptsname(pseudouser);
FILE *pout = fdopen(pseudouser, "r+");

free(popen(pseudo_sprintf("screen tty.MobileRobot-RNI-SPP >\"%s\" 2>\"%s\" <\"%s\"", pseudoname, pseudoname, pseudoname)));

do stuff with pout

pseudo_sprintf替换为真实的snprintf调用和适当的缓冲。

关于c++ - 如何在C++中使用popen打开 "screen"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53380388/

相关文章:

c++ - 重载运算符

c++ - 重新加载未定义的行为和序列点

macos - Nginx : Cannot listen on port 80 . .. 只有端口 8080 在 OSX 10.11 上工作

c - ld : can't open output file for writing: bin/s, errno=2 架构 x86_64

c++ - 如何使继承的基类使用公共(public)变量

c++ - 当通知程序/信号超出范围时,取消分配 boost 绑定(bind)中的回调监听器对象

Python-Application .desktop-shortcut 导致故障

linux - 在多核机器 Linux OS 中,当进程调度程序将一个进程迁移到另一个 cpu 时

c - libnl 中 nl_socket_set_cb() 的目的

linux - 多平台 Amazon-AWS 开发