c - 用叉子处理几个管道
问题描述
我必须做一个非常简单的 shell,它接受一个命令作为参数,例如:
./a.out "/bin/ls" "|" "/usr/bin/grep/" "m" "|" "/usr/bin/grep" "u"
该命令将始终有效(没有语法错误),我只需要处理管道。我已经有我的 ast 工作,但我在执行部分有问题。这是我的 ast 结构:
struct s_ast
{
int t; // type (either PIPE or CMD)
t_ast *l; // left node (or NULL it t == CMD)
t_ast *r; // right node (or NULL it t == CMD)
char **c; // the command with its args (or NULL if t == PIPE)
};
这是执行部分的代码:
void exe_pipe(t_ast *ast, char **env)
{
int fd[2], pid = 0;
if (pipe(fd) < 0 || (pid = fork()) < 0)
{
error(NULL, NULL);
}
if (pid == 0)
{
dup2(fd[1], STDOUT_FILENO);
close(fd[0]);
close(fd[1]);
exe(ast->l, env);
exit(0);
}
// EDIT: I don't fork anymore for the right side of a PIPE node
dup2(fd[0], STDIN_FILENO);
close(fd[1]);
close(fd[0]);
exe(ast->r, env);
waitpid(pid, NULL, 0);
}
它运行良好,对于每个简单的命令,我都会得到预期的结果,但是如果我给出一个带有很多管道的大命令,我会得到Error: fork error
消息。为了测试它,我曾经ulimit -Su 300
减少了同时运行的最大授权进程数,并且我向程序传递了一个带有一百个管道的命令。
我尝试了几件事,但我不知道如何输入管道数量超过允许的最大进程数的命令。
解决方案
推荐阅读
- java - 如何使用白盒为按钮编写单元测试?
- java - Apache Commons Math 中 DBSCAN 的自定义距离度量(v3.1 与 v3.6)
- angular - RXJS:返回外部 observable 的操作值
- unit-testing - 如何在库项目中测试 Yii2 模型?
- java - 错误:使用 Forge 启动 Minecraft 1.12.2 时无法找到或加载主类 net.minecraft.launchwrapper.Launch
- c# - asp.net核心中的部分标签助手和HTML助手有什么区别?
- r - 将数据加载到 Rstudio
- java - 如何用 0 在 1 的位置反转一个数字?
- html - 将单位添加到数字
- sql-server - 如何在服务器上托管 React/Node Web 应用程序