经与管道,叉,dup2问题 [英] Having issues with pipe, fork, dup2

查看:99
本文介绍了经与管道,叉,dup2问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的管道,叉,dup2实施的ls |更多或LS |排序等。
我只是不能够了解这里的问题。
当我运行我的程序,我得到这个错误:

I am using pipes, fork , dup2 to implement "ls | more" or "ls | sort" etc. I am just not able to understand the issue here. When I run my program, I get this error:

./a.out  
Missing filename ("less --help" for help)

为什么会出现少??

Why am I getting "less" ??

什么是错的这个code?如果我改变多为LS再次,它工作正常。我的意思是,它像做LS | LS。

What is wrong with this code ? If I change "more" to "ls" again, it works fine. I mean, its like doing ls | ls.

#define STDIN 0
#define STDOUT 1

int main()
{
   int fd[2];
   int pid;
   char *lschar[20]={"ls",NULL};
   char *morechar[20]={"more",NULL};
   pid = fork();
   if (pid == 0) {
   /* child */
     int cpid;
     cpid = fork();
     if(cpid == 0) {
       //printf("\n in ls \n");
       pipe(fd);
       dup2(fd[1], STDOUT);
       close(fd[0]);
       close (fd[1]);
       execvp("ls",lschar);
     } else if(cpid>0) {
       waitpid(cpid, NULL,0);
       dup2(fd[0],STDIN);
       close(fd[0]);
       close(fd[1]);
       execvp("more", morechar);
     }
   } else if (pid > 0) {
     /* Parent */
     waitpid(pid, NULL,0);
   }
   return 0;
}

鸭preciate你的帮助。

Appreciate your help.

推荐答案

您的主要问题出在你的管道()调用的位置。之前,你必须把它的 的你叉()

Your main problem lies in your placement of the pipe() call. You must call it before you fork():

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>

#define STDIN 0
#define STDOUT 1

int main()
{
  int fd[2];
  int pid;
  char *lschar[20]={"ls",NULL};
  char *morechar[20]={"more", NULL};
  pid = fork();
  if (pid == 0) {
    /* child */
    int cpid;
    pipe(fd);
    cpid = fork();
    if(cpid == 0) {
      //printf("\n in ls \n");
      dup2(fd[1], STDOUT);
      close(fd[0]);
      close (fd[1]);
      execvp("ls",lschar);
    } else if(cpid>0) {
      dup2(fd[0],STDIN);
      close(fd[0]);
      close(fd[1]);
      execvp("more", morechar);
    }
  } else if (pid > 0) {
    /* Parent */
    waitpid(pid, NULL,0);
  }
  return 0;
}

否则,该多个工艺不具有正确的文件描述符。此外,waitpid函数()在多个处理是有问题的和不必要的(更会等待自行输入)。如果LS有一个特别长的输出管道可以得到充分造成LS在其写入阻塞。其结果是一个僵局,它永远等待。因此,我也将删除违规 waitpid函数()电话。

另外,如果你做检查的函数的返回值如管道()的一个很好的做法 dup2()这个错误本来更容易找到 - 你会看到你的 dup2()是失败

Also, if you make a good practice of checking the return values of functions like pipe() and dup2() this error would have been much easier to find -- you would have seen that your dup2() was failing.

这篇关于经与管道,叉,dup2问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆