我正在linux中试验这个dup2命令。我写了一个代码,代码如下:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
int pipe1_ends[2];
int pipe2_ends[2];
char string[] = "this \n is \n not \n sorted";
char buffer[100];
pid_t pid;
pipe(pipe1_ends);
pipe(pipe2_ends);
pid = fork();
if(pid > 0) { /* parent */
close(pipe1_ends[0]);
close(pipe2_ends[1]);
write(pipe1_ends[1],string,strlen(string));
read(pipe2_ends[0], buffer, 100);
printf("%s",buffer);
return 0;
}
if(pid == 0) { /* child */
close(pipe1_ends[1]);
close(pipe2_ends[0]);
dup2(pipe1_ends[0], 0);
dup2(pipe2_ends[1],1);
char *args[2];
args[0] = "/usr/bin/sort";
args[1] = NULL;
execv("/usr/bin/sort",args);
}
return 0;
}我希望这个程序的行为如下:它应该派生一个子代,并用排序过程替换它的图像。由于标准输入和标准输出被替换为dup2命令,因此我期望排序从管道读取输入,并将输出写入父管道打印的另一个管道。但是排序程序似乎没有读取任何输入。如果没有给出命令行参数,sort会从stdin中读取它,对吗?有人能帮我解决这个问题吗?
非常感谢!
发布于 2013-05-22 02:12:52
嗯。发生的情况是您没有完成写入:在将数据发送到子进程之后,您必须通过关闭pipe1_ends1或对其调用shutdown(2)来告诉它您已经完成了写入。您还应该在循环中调用write/read,因为在一般情况下,read至少不会一次性给出所有结果。显然,完整的代码会检查所有返回值,不是吗?
最后一件事:你的printf被严重损坏了。它只能接受以null结尾的字符串,并且read返回的结果不会以null结尾(它是一个带长度的缓冲区,这是知道结尾位置的另一种常见方法)。您需要:
int n = read(pipe2_ends[0], buffer, 99);
if (n < 0) { perror("read"); exit(1); }
buffer[n] = 0;
printf("%s",buffer);https://stackoverflow.com/questions/16676139
复制相似问题