0
以下代码的用途是创建2个子进程。其中一个将执行'ls'。另一个将使用'ls'的输出执行'排序'。两个儿童进程都通过管道来实现这一点。代码工作,但是,输出格式不是我所期望的。管道过程的输出与预期不完全相同。为什么? (C,UNIX)
代码:minishell.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
`int main()
{
int fd[2];
pipe(fd);`
//First child process created: ls
if (fork() == 0) {
/*child */
close(fd[0]);
dup2(fd[1], STDOUT_FILENO);
close(fd[1]);
execlp("ls", "ls", (char *)0);
fprintf(stderr, "execlp(ls) failed\n");
exit(1);
}
wait(NULL);
//Second child process created: sort
if (fork() == 0) {
close(fd[1]);
dup2(fd[0], STDIN_FILENO);
close(fd[0]);
execlp("sort", "sort", (char *)0);
fprintf(stderr, "execlp(sort) failed\n");
exit(1);
}
close(fd[0]);
close(fd[1]);
wait(NULL);
fprintf(stderr, "parent done\n");
return 0;
}
预期输出:LS |排序
8.bmp bmplib.h Downloads/ lab4.c Music/ tester
appData/ bmptool.c example.bmp Makefile myls.c testfile.c
bitcount.c Documents/ infile minishell.c Pictures/ Videos/
bitcount* Desktop/ fork.c minishell* myshell.c Testfile.txt
bmplib.c doublefork.c lab4* Movies/ temp/
我的输出:./minishell
8.bmp
appData
bitcount
bitcount.c
bmplib.c
bmplib.h
bmptool.c
Desktop
Documents
doublefork.c
Downloads
example.bmp
fork.c
infile
lab4
lab4.c
Makefile
minishell
minishell.c
Movies
Music
myls.c
myshell.c
Pictures
temp
tester
testfile.c
Testfile.txt
Videos
parent done
- 为什么格式化两种情况之间有什么不同?
- 在./minishell的情况下,为什么要从所有文件夹名称中删除“/”?
- 在的情况下|排序,为什么某些文件夹出现在'myshell.c'之前的'Pictures /';'Testfile.txt'之前的'Videos /')显然不符合字典顺序?
*我试过用ls -l |排序,然后./minishell(将第一个孩子的execlp当然添加“-l”后),输出结果是相同的,除了从每个文件夹名称中删除“/”。
我的假设是它与管道有关。我认为这两个过程,孤立的'ls'和'sort'工作都很好。然而,当其中一个写入/读取管道时发生了一些问题。我非常努力地找到潜在的问题无济于事。任何帮助将不胜感激。提前致谢。