使用fork(),execlp()和dup2()
我正在编写一个C程序,该程序将运行Linux命令,例如:
ls -al | grep "main" | sort
我只是用孩子来做到这一点。 (当我使用父母执行最后一个,但我只想使用孩子时,它起作用了)
我有一个问题,这是第二叉之前执行的最后一个叉子。 这将运行此命令ls -al |排序| grep“ main”
在此示例中,结果是相同的,但其他结果是错误的。
我如何在最后一个叉子中等待第二个叉子?
代码 :
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#define READ 0
#define WRITE 1
int main(int argc, char *argv[])
{
pid_t pid;
int fd[2],fd1[2];
pipe(fd);pipe(fd1);
pid = fork();
if (pid == 0)
{
close(fd1[READ]);close(fd1[WRITE]);close(fd[READ]);
printf("i'm the child used for ls \n");
dup2(fd[WRITE], STDOUT_FILENO);
close(fd[WRITE]);
execlp("ls", "ls", "-al", NULL);
}
else
{
pid = fork();
if (pid == 0)
{
close(fd1[READ]);close(fd[WRITE]);
printf("i'm in the second child, which will be used to run grep\n");
dup2(fd[READ], STDIN_FILENO);
close(fd[READ]);
close(fd1[READ]);close(fd[WRITE]);
dup2(fd1[WRITE], STDOUT_FILENO);
close(fd1[WRITE]);
execlp("grep", "grep", "main", NULL);
}
else
{
pid = fork();
if (pid == 0)
{
/* code */
close(fd[READ]);close(fd[WRITE]);close(fd1[WRITE]);
printf("i'm in the third child, which will be used to run (sort)\n");
dup2(fd1[READ], STDIN_FILENO);
close(fd1[READ]);
execlp("sort", "sort", NULL);
}
}
}
return 0;
}
I am writing a C program which will run Linux commands, like:
ls -al | grep "main" | sort
I used just the children to do that. (it work when I use the parent to execute the last one but I want to use just the children )
I have a problem that is the last fork execute before the second fork.
and that will run this command ls -al | sort | grep "main"
in this example the result is the same but with others is wrong.
how can I wait the second fork in the last fork ?.
code :
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#define READ 0
#define WRITE 1
int main(int argc, char *argv[])
{
pid_t pid;
int fd[2],fd1[2];
pipe(fd);pipe(fd1);
pid = fork();
if (pid == 0)
{
close(fd1[READ]);close(fd1[WRITE]);close(fd[READ]);
printf("i'm the child used for ls \n");
dup2(fd[WRITE], STDOUT_FILENO);
close(fd[WRITE]);
execlp("ls", "ls", "-al", NULL);
}
else
{
pid = fork();
if (pid == 0)
{
close(fd1[READ]);close(fd[WRITE]);
printf("i'm in the second child, which will be used to run grep\n");
dup2(fd[READ], STDIN_FILENO);
close(fd[READ]);
close(fd1[READ]);close(fd[WRITE]);
dup2(fd1[WRITE], STDOUT_FILENO);
close(fd1[WRITE]);
execlp("grep", "grep", "main", NULL);
}
else
{
pid = fork();
if (pid == 0)
{
/* code */
close(fd[READ]);close(fd[WRITE]);close(fd1[WRITE]);
printf("i'm in the third child, which will be used to run (sort)\n");
dup2(fd1[READ], STDIN_FILENO);
close(fd1[READ]);
execlp("sort", "sort", NULL);
}
}
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论