gpt4 book ai didi

c - 使用除 cat 之外的命令进行重定向

转载 作者:行者123 更新时间:2023-11-30 17:19:06 30 4
gpt4 key购买 nike

我正在开发个人 shell 并开始实现重定向。

“<”工作得很好,而“>”仅适用于 cat 命令。

这是处理“>”效果的代码:

int     write_in_file(char **tab, int fd)
{
int count;
char i;

if (strncmp("cat", tab[0], 3) == 0)
{
while ((count = read(0, &i, 1)) > 0)
write(fd, &i, 1);
exit(1);
}
else if (strncmp("ls", tab[0], 2) == 0)
{
/* Here handle other commands then cat */
}
else
return (0);
}

如你所见,当 shell 识别时

cat > file

它做了它应该做的事情:让用户写入所述文件。但现在我希望处理其他命令,例如

ls > file
man ascii > file

你们知道我该怎么做吗?如果您需要任何精度,请告诉我,

编辑:请注意,在此函数中我处于子进程中。

提前致谢。

最佳答案

I/O 重定向如何工作

当 shell 调用 exec 时(例如启动cat或man),程序将继承之前设置的所有文件句柄。程序将使用 0 作为 stdin,1 作为 stdout,2 作为 stderr。如果您想将输出重定向到文件,您将打开输出文件并使用 dup2将其设置为文件号 1。通常所有这些都是在 fork 之后完成的。 .

参见GNU C Library: Duplicating DescriptorsGNU C Library: Launching jobs

您可能需要的其他工具

您不应该使用strncmp(command, "cat", 3)检查命令是否为 cat,因为这也将匹配 catman 或 catdvi,但不匹配“cat”。相反,使用分词器,例如strtok .

参见The Gnu C Library: Finding Tokens in a String

关于c - 使用除 cat 之外的命令进行重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28961508/

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