簡體   English   中英

重定向到execlp()

[英]Redirect to execlp()

我對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在第二個表中

您可能想使用dup2重定向stdin和stdout。 另外,您沒有正確使用execlp。 它期望可變數量的參數以NULL指針終止。 並且正如注釋所建議的那樣,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