我有一个 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_openpt
和 ptsname
得到这些。
伪代码(非线程安全):
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/