我编写了一个程序,在 Linux 终端中使用 ls 命令来读取文件夹的内容,并使用我的 C 程序将 ls 中的文本写入屏幕。这是我写的代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int pipe_ends[2];
if(pipe(pipe_ends))
{
printf("Could not create pipe\n");
return -1;
}
pid_t pid = fork();
if(pid < 0)
{
perror("fork");
exit(1);
}
if(!pid)
{
dup2(pipe_ends[0],1);
char* args[3];
args[0] = "/bin/ls";
args[1] = "-l";
args[2] = NULL;
execv("/bin/ls",args);
printf("something went wrong\n");
}
char buff[10240];
int count = read(pipe_ends[1],buff,10240);
buff[count] = '\0';
printf("here goes nothing......\n");
printf("%s",buff);
return 0;
}
我为这个程序得到的输出是:
here goes nothing......
od@od-Inspiron-N5110:~/Documents/work/new/CO/project1$ /bin/ls: write error: Bad file descriptor
od@od-Inspiron-N5110:~/Documents/work/new/CO/project1$
似乎在写作之前已经完成了阅读。但我认为阅读是阻塞的。请帮我在这里找到错误。
提前致谢。