简体   繁体   English

重定向到execlp()

[英]Redirect to execlp()

I have a problem with execlp. 我对execlp有问题。 When I do not know how to redirect command from arrays of pointers to execlp correctly. 当我不知道如何将命令从指针数组正确重定向到execlp时。 For example i want to use 例如我想使用

ls -l | sort -n

my program takes only "ls" and "sort" 我的程序只接受“ ls”和“ sort”

      int pfds[2];
      pipe(pfds);
      child_pid = fork();
      if(child_pid==0)
      {       
        close(1);
            dup(pfds[1]);   
            close(pfds[0]); 
            execlp(*arg1, NULL);

      }
      else 
      {
        wait(&child_status); 
            close(0);
        dup(pfds[0]);
        close(pfds[1]); 
            execlp(*arg2, NULL);
      }

All commands are in arrays of pointers where: ls -l is in first table and sort -n in second 所有命令都在指针数组中,其中: ls -l在第一个表中,而sort -n在第二个表中

You probably wanted to use dup2 to redirect stdin and stdout. 您可能想使用dup2重定向stdin和stdout。 Also you are not using execlp correctly. 另外,您没有正确使用execlp。 It expects variable number of parameters terminated by NULL pointer. 它期望可变数量的参数以NULL指针终止。 And as suggested by comments, the wait command shall not be there. 并且正如注释所建议的那样,wait命令将不存在。

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

int main() {
    int pfds[2];
    pipe(pfds);
    int child_pid;
    child_pid = fork();
    if(child_pid==0)
    {       
        dup2(pfds[1], 1);   
        close(pfds[0]); 
        execlp("ls", "-al", NULL);

    }
    else 
    {
        dup2(pfds[0], 0);
        close(pfds[1]); 
        execlp("sort", "-n", NULL);
    }
}

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

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