0

我对 execlp 有疑问。当我不知道如何将命令从指针数组正确重定向到 execlp 时。例如我想使用

ls -l | sort -n

我的程序只需要“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);
      }

所有命令都在指针数组中,其中:ls -l在第一个表中,sort -n在第二个表中

4

1 回答 1

0

您可能想使用 dup2 重定向标准输入和标准输出。此外,您没有正确使用 execlp。它期望由 NULL 指针终止的可变数量的参数。正如评论所建议的那样,等待命令不应存在。

#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);
    }
}
于 2014-01-08T17:41:17.980 回答