gpt4 book ai didi

c++ - 带有文件输入的 exec 系列

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:01:28 24 4
gpt4 key购买 nike

大家好,我正在尝试用 C++ 编写一个 shell,但我在使用带有 exec 命令的输入文件的功能时遇到了问题。例如,Linux 中的 bc shell 可以执行“bc < text.txt”,它可以像时尚一样批量计算文本中的行。我正在尝试对我的 shell 做同样的事情。类似的东西:

char* input = “input.txt”;
execlp(input, bc, …..) // I don’t really know how to call the execlp command and all the doc and search have been kind of cryptic for someone just starting out.

这甚至可以通过 exec 命令实现吗?还是我必须逐行阅读并在 for 循环中运行 exec 命令??

最佳答案

您可以打开文件,然后 dup2() 将文件描述符发送到标准输入,或者您可以关闭标准输入,然后打开文件(这是有效的,因为标准输入是描述符 0 和 open() 返回编号最小的可用描述符)。

 const char *input = "input.txt";
int fd = open(input, O_RDONLY);
if (fd < 0)
throw "could not open file";
if (dup2(fd, 0) != 0) // Testing that the file descriptor is 0
throw "could not dup2";
close(fd); // You don't want two copies of the file descriptor
execvp(command[0], &command[0]);
fprintf(stderr, "failed to execvp %s\n", command[0]);
exit(1);

您可能需要比 throw 更聪明的错误处理,尤其是因为这是子进程,而父进程需要知道。但是 throw 站点标记了处理错误的点。

注意 close()

关于c++ - 带有文件输入的 exec 系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7630085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com