如何解决我是否以正确的方式编写一个使用管道执行命令的程序?
我正在编写一个接受字符串的程序,以我为例
ls | wc -c | grep 4
我正在训练使用 fork、pipes 和 dup2、execve 执行它。
我写了一个有效的代码,但它看起来像一个超长的代码,我担心我走错了方向。
- 有一个主循环处理第一个命令、最后一个命令和最后所有其他命令的情况是否正常?中间?
- 必须精确关闭在 execve 之前使用过的每个 fd 是否正常?这对于 3 个相同的情况(第一个命令,最后一个命令和其他)?
这是我的代码:
i = 0;
while (i < nbpipe + 1)
{
pid = fork();
if (pid < 0) //I'm gonna secure this kind of thing later
return (-1);
//close,dup2 and execve according to the 3 recovered commands
if (pid == 0 && i == 0)
{
close_first(i + 1,nbpipe,fd);
dup2(fd[0][1],1);
execve(all[i][0],all[i],NULL);
}
else if (pid == 0 && i == nbpipe)
{
close_last(i - 1,fd);
dup2(fd[nbpipe - 1][0],0);
execve(all[i][0],NULL);
}
else if (pid == 0)
{
close_all(i - 1,fd);
dup2(fd[i - 1][0],0);
dup2(fd[i][1],NULL);
}
//I close all pipes that have not been closed after being executed by execve
//I know this is not dynamic yet according to the i of my loop (but it works for the example)
if (i == 0)
{
close(fd[0][1]);
}
else if (i == nbpipe)
{
close(fd[1][0]);
}
else
{
close(fd[0][0]);
close(fd[1][1]);
}
i++;
}
wait(&pid);
wait(&pid);
wait(&pid);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。