gpt4 book ai didi

c - 在 C 中实现 << 重定向

转载 作者:行者123 更新时间:2023-11-30 15:02:22 25 4
gpt4 key购买 nike

我正在尝试实现<< C 中的重定向,我在使用下面的代码时遇到问题。我可以实现其他三个重定向< , > ,和>> 。我想我需要一个循环来处理/检查 << 的分隔符,我该如何处理这个问题?当我运行该程序时,我得到

 /usr/bin/cat: '<<': No such file or directory
/usr/bin/cat: EOF: No such file or directory

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>

int main(void)
{
char *argv[] = { "/usr/bin/cat", "<<", "EOF", 0 };
char *envp[] =
{
"HOME=/",
"PATH=/bin:/usr/bin",
"USER=julekgwa",
0
};
int fd = open(0, O_RDONLY);
dup2(fd, 0);
close(fd);
execve(argv[0], &argv[0], envp);
fprintf(stderr, "Oops!\n");
return -1;
}

最佳答案

任何类型的重定向都是 shell 功能。您正在使用 execve 直接执行 cat,而不给 shell 执行任何操作的机会。

以下方法可能有效:

char *argv[] = { "/bin/bash", "-c", "/usr/bin/cat <<EOF\ntest\nEOF", 0};

但您不太可能真的想这样做。

关于c - 在 C 中实现 << 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41082647/

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