C管道编程:使用管道传递数据

C管道编程:使用管道传递数据,c,linux,pipe,C,Linux,Pipe,我刚刚编写了以下代码:- #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { // Create a pipe int fd[2]; pipe(fd); int i; close(0); //close the input to this process dup(fd[0]); // duplicate the

我刚刚编写了以下代码:-

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

// Create a pipe
int fd[2];
pipe(fd);

int i;

close(0); //close the input to this process
dup(fd[0]); // duplicate the input of this pipe to 0, so that stdin now refers to the input of the pipe

char *test[3] = {"A", "B", "C"};

for ( i=0 ; i < 3; ++i ) {
    write(fd[0], test[i], strlen(test[i]));
    write(fd[0], '\n', 1);
}

execlp("sort", "sort", NULL);

return 0;
}
#包括
#包括
#包括
#包括
int main(){
//创建一个管道
int-fd[2];
管道(fd);
int i;
关闭(0);//关闭此进程的输入
dup(fd[0]);//将此管道的输入复制到0,以便stdin现在引用管道的输入
字符*测试[3]={“A”、“B”、“C”};
对于(i=0;i<3;++i){
写入(fd[0],测试[i],strlen(测试[i]);
写入(fd[0],'\n',1);
}
execlp(“排序”,“排序”,空);
返回0;
}

我希望有
sort
从管道
fd[1]
的输出中获取输入,并将排序后的输出打印到stdout

首先,检查系统调用中的错误。你会看到一个EBADF

r = write(fd[0], ...);
if (r == -1 && errno == EBADF) oops();
其次,写入管道的写入端:

r = write(fd[1], ...); /* Not fd[0] ! */
第三,将换行符作为字符串而不是字符传递:

r = write(fd[1], "\n", 1); /* Not '\n' */
第四,完成后关闭管道的写入端,否则,
sort(1)
将永远阻止从未到达的输入:

for (...) {
  r = write(fd[1], ...);
}
close(fd[1]);

execlp("sort", "sort", NULL);
oops_exec_failed();

首先,检查系统调用中的错误。你会看到一个EBADF

r = write(fd[0], ...);
if (r == -1 && errno == EBADF) oops();
其次,写入管道的写入端:

r = write(fd[1], ...); /* Not fd[0] ! */
第三,将换行符作为字符串而不是字符传递:

r = write(fd[1], "\n", 1); /* Not '\n' */
第四,完成后关闭管道的写入端,否则,
sort(1)
将永远阻止从未到达的输入:

for (...) {
  r = write(fd[1], ...);
}
close(fd[1]);

execlp("sort", "sort", NULL);
oops_exec_failed();