【问题标题】:exec family with a file input带有文件输入的 exec 系列
【发布时间】:2011-10-03 00:10:18
【问题描述】:

大家好,我正在尝试用 C++ 编写一个 shell,但我在使用 exec 命令的输入文件的功能上遇到了问题。例如,Linux 中的 bc shell 能够执行“bc

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 命令??

【问题讨论】:

  • execlp 用于启动单个进程。您必须逐行读取输入文件并单独处理每个命令。
  • execlp() 仅在您知道编译时的命令和参数时才真正有用,这对于 shell 来说很少见。您应该假设您将使用 exec*() 系列函数的 execv*() 部分。

标签: c++ linux shell input exec


【解决方案1】:

你可以打开文件然后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()

【讨论】:

    【解决方案2】:

    重定向是由 shell 执行的——它不是bc 的参数。你可以调用 bash(相当于bash -c "bc &lt; text.txt"

    例如,您可以将execvp"bash" 的文件参数和参数列表一起使用

    "bash"
    "-c"
    "bc < text.txt"
    

    【讨论】:

    • 如果他正在编写一个shell,他不应该使用任何其他shell来处理这个。
    • @BenVoigt 确实如此,但“Linux 中的 bc shell 能够执行“bc bc 命令
    猜你喜欢
    • 2016-04-09
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多