1

我正在使用一些管道和叉子来执行类似的命令

猫文件.tar.gz | myprogram -c "tar -zvt" -i "remoteMachineIp"

但如果我这样做

我的程序 -c “bash” -i “remoteMachineIp”

bash 没问题,但没有 tty。如果没有 tty,如果我调用 vim 命令,它会打开 vi 混乱。

我如何使用 tty 在 execlp 上调用 bash。

代码示例

if(cm->pid2==0){ //pipe and fork to send data to my execlp
close(cm->fout[0]);
dup2(cm->fout[1], 1);
execlp("bash", "bash", "-c", command.c_str(), NULL); // command is mycommand so is bash -c "bash"
}
else{
close(cm->fout[1]);
while((size=read(cm->fout[0], buffer, 2000)) > 0){
cm->message->send(buffer, size); //send the data to my program
}
//Close it and send the return code

问题是 execlp 将 bash 返回给我,但没有 tty

我如何用 tty 调用 bash?

谢谢

4

1 回答 1

1

我猜您担心的是您启动的命令继承stdin自其父级 ( myprogram),而其父级的命令stdin是从cat file.tar.gz. 您想运行一个强制从 tty 读取数据的子进程,而不是继承的stdin管道。

您可以打开/dev/tty以获取对 tty 的引用。如果没有 tty,它将失败。例如:

close(0);
open("/dev/tty", O_RDWR);
/* The file descriptor returned by open should be 0 */

但是,我注意到您将子命令重定向stdout到程序的管道。如果您正在执行的命令exec是交互式的,则这将不起作用。交互式命令需要将其输入和输出都连接到 tty。stdin无论您是否连接到 tty ,启动一个输出连接到管道的交互式命令可能没有任何意义。

顺便说一句:你为​​什么使用bash -c <command>而不是sh -c <command>在你的execlp?这样,您就引入了对bash您真正需要的地方的不必要的依赖,即标准 POSIX bourne shell shexecing throughsh -c是通过 shell 启动命令的标准方法。例如,这就是由 完成的system()

于 2012-05-14T16:04:37.387 回答