简体   繁体   English

无法使用execlp从管道读取

[英]can not read from pipe with execlp

For an assignment, i am supposed to implement the linux terminal. 对于作业,我应该实现linux终端。 My terminal should support arguments with pipes. 我的终端应使用管道支持参数。 Like the user can input: ls | grep ".cpp" 像用户可以输入: ls | grep ".cpp" ls | grep ".cpp" What i have done so far is: ls | grep ".cpp"到目前为止,我所做的是:

pid = fork();
if(pid==0)
{
  close(fd[0]);
  dup2(fd[1],1);
  close(fd[1]);
  execlp("/bin/ls","ls");
}
wait(NULL);
pid=fork();
if(pid==0)
{
  close(fd[1]);
  dup2(fd[0],0);
  close(fd[0]);
  execlp("/bin/grep","grep",".cpp");
}

my first child works perfectly, writes the output of ls into a pipe declared earlier, however, my second child runs grep, but it apparently can not get input from pipe. 我的第一个孩子运行良好,将ls的输出写入到先前声明的管道中,但是,我的第二个孩子运行grep,但显然无法从管道中获取输入。 Why is that so? 为什么会这样? when i run it, my output is /root/OS $ ls | 当我运行它时,我的输出是/ root / OS $ ls | grep grep的

it just gets stuck like this 就这样被卡住了

Don't ignore compiler warnings: 不要忽略编译器警告:

$ gcc lol.c
lol.c: In function ‘main’:
lol.c:14:5: warning: not enough variable arguments to fit a sentinel [-Wformat=]
     execlp("/bin/ls","ls");
     ^
lol.c:23:5: warning: missing sentinel in function call [-Wformat=]
     execlp("/bin/grep","grep",".cpp");
     ^

Here's man execlp : 这是man execlp

The first argument, by convention, should point to the filename associated with the file being executed. 按照惯例,第一个参数应指向与正在执行的文件关联的文件名。 The list of arguments must be terminated by a NULL pointer, and, since these are variadic functions, this pointer must be cast (char *) NULL. 参数列表必须以NULL指针终止,并且由于它们是可变参数函数,因此必须将该指针强制转换为(char *)NULL。

Always compile with -Werror so that compilation fails if there are warnings, and preferably also with -Wall to get warnings for all potential issues. 始终使用-Werror编译,以便在出现警告时编译失败,最好也使用-Wall来获取所有潜在问题的警告。

Here's your program with a main method and sentinels added: 这是您的程序,带有主要方法和添加的标记:

#include <unistd.h>
#include <sys/wait.h>


int main() {
  int fd[2];
  int pid;

  pipe(fd);
  pid = fork();
  if(pid==0)
  { 
    close(fd[0]);
    dup2(fd[1],1);
    close(fd[1]);
    execlp("/bin/ls","ls", NULL);
  }
  wait(NULL);
  pid=fork();
  if(pid==0)
  { 
    close(fd[1]);
    dup2(fd[0],0);
    close(fd[0]);
    execlp("/bin/grep","grep",".cpp", NULL);
  }
  return 0;
}

Here's how it runs now: 现在是这样运行的:

$ gcc -Wall -Werror lol.c -o lol
$ ./lol
foo.cpp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM