【发布时间】:2013-05-28 09:17:51
【问题描述】:
我需要创建两个子进程。一个子进程需要运行命令“ls -al”并将其输出重定向到下一个子进程的输入,该子进程又将对其输入数据运行命令“sort -r -n -k 5”。最后,父进程需要读取它(数据已经排序)并将其显示在终端中。终端中的最终结果(执行程序时)应该和我直接在 shell 中输入以下命令一样:“ls -al | sort -r -n -k 5”。为此,我需要使用以下方法:pipe()、fork()、execlp()。
我的程序可以编译,但我没有得到想要的输出到终端。我不知道出了什么问题。代码如下:
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main()
{
int fd[2];
pid_t ls_pid, sort_pid;
char buff[1000];
/* create the pipe */
if (pipe(fd) == -1) {
fprintf(stderr, "Pipe failed");
return 1;
}
/* create child 2 first */
sort_pid = fork();
if (sort_pid < 0) { // error creating Child 2 process
fprintf(stderr, "\nChild 2 Fork failed");
return 1;
}
else if(sort_pid > 0) { // parent process
wait(NULL); // wait for children termination
/* create child 1 */
ls_pid = fork();
if (ls_pid < 0) { // error creating Child 1 process
fprintf(stderr, "\nChild 1 Fork failed");
return 1;
}
else if (ls_pid == 0) { // child 1 process
close(1); // close stdout
dup2(fd[1], 1); // make stdout same as fd[1]
close(fd[0]); // we don't need this end of pipe
execlp("bin/ls", "ls", "-al", NULL);// executes ls command
}
wait(NULL);
read(fd[0], buff, 1000); // parent reads data
printf(buff); // parent prints data to terminal
}
else if (sort_pid == 0) { // child 2 process
close(0); // close stdin
dup2(fd[0], 0); // make stdin same as fd[0]
close(fd[1]); // we don't need this end of pipe
execlp("bin/sort", "sort", "-r", "-n", "-k", "5", NULL); // executes sort operation
}
return 0;
}
【问题讨论】:
-
除非您是从
/执行,否则请尝试将“bin/ls”替换为“/bin/ls”(类似于“/bin/sort”) -
看来您没有进行错误检查。您应该添加一些,这将有助于您诊断问题。
-
我在子块中有 printf() 语句。没有“/”,它会显示两个子语句,但是当我输入“/”时,它不会显示这些语句;就像它没有到达儿童块一样。
-
顺便说一句:如果路径名中没有“/”,则 execlp() 和 execvp() 执行 PATH 搜索。这都可以在 The Fine Manual 中阅读。 Thay 还可以返回(错误时)检查返回值,如果返回则 errno。
-
这种疾病从哪里开始在字符串的开头而不是结尾打印换行符,如
fprintf(stderr, "\nChild 2 Fork failed");?