带有文件输入的Exec族

exec family with a file input

本文关键字:Exec 输入 文件      更新时间:2023-10-16

嘿,伙计们,我正试图用c++写一个shell,我在使用exec命令输入文件的功能方面遇到了麻烦。例如,Linux中的bc shell能够执行"bc <text.txt",它以批处理的方式计算文本中的行。我正试图对我的壳做同样的事情。类似以下语句:>

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 %sn", command[0]);
 exit(1);

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

注意close()

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

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

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