首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在dup2中使用排序

在dup2中使用排序
EN

Stack Overflow用户
提问于 2013-05-22 01:36:24
回答 1查看 399关注 0票数 1

我正在linux中试验这个dup2命令。我写了一个代码,代码如下:

代码语言:javascript
复制
#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中读取它,对吗?有人能帮我解决这个问题吗?

非常感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-22 02:12:52

嗯。发生的情况是您没有完成写入:在将数据发送到子进程之后,您必须通过关闭pipe1_ends1或对其调用shutdown(2)来告诉它您已经完成了写入。您还应该在循环中调用write/read,因为在一般情况下,read至少不会一次性给出所有结果。显然,完整的代码会检查所有返回值,不是吗?

最后一件事:你的printf被严重损坏了。它只能接受以null结尾的字符串,并且read返回的结果不会以null结尾(它是一个带长度的缓冲区,这是知道结尾位置的另一种常见方法)。您需要:

代码语言:javascript
复制
int n = read(pipe2_ends[0], buffer, 99);
if (n < 0) { perror("read"); exit(1); }
buffer[n] = 0;
printf("%s",buffer);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16676139

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档