簡體   English   中英

管道&執行&C

[英]Pipes & exec & C

嗨,我有以下問題,我必須創建一個執行這些Linux命令的程序ls –la | sort | wc –l ls –la | sort | wc –l ls –la | sort | wc –l但是在我的代碼中我只能讀到該命令中的兩個,可以用這個幫助我嗎?

int main(){
  pid_t pids[3];
   int dados[2],dados2[2],i;

    if(pipe(dados) == -1 && pipe(dados2) == -1){
       perror("pipe failed");
       exit(1);
     }

  for(i=0;i<3;i++){
      pids[i] = fork();
      if(pids[i] == 0){ 
          if(i==0){
            close(dados[0]);
            dup2(dados[1],1);
            close(dados[1]);

            execlp("ls","ls","-la",NULL);
            perror("exec failed");
            exit(-1);
        }
        if(i==1){
            close(dados[1]);
            dup2(dados[0],0);
            close(dados[0]);


            close(dados2[0]);
            dup2(dados2[1],1);
            close(dados2[1]);

            execlp("sort","sort",NULL);
            perror("exec failed");
            exit(-1);
         }else{
            close(dados2[1]);
            dup2(dados2[0],0);
            close(dados2[0]);
            printf("aaaaaaaaaaaaaaaaaa");
            execlp("wc","wc","-l",NULL);
            perror("exec failed");
            exit(-1);
         }
     }
 }

 /* Pai tem de fechar a sua copia da extremidade de escrita 
  para a leitura do sort desbloquear */
 close(dados[1]);
 close(dados2[0]);
 for(i=0;i<3;i++){
     wait(NULL);
 }

return 0;

}

我不明白這是什么小姐

立即引起我注意的是

-if(pipe(dados) == -1 && pipe(dados2) == -1){
+if(pipe(dados) == -1 || pipe(dados2) == -1){

   perror("pipe failed");
   exit(1);
}

父pid僅需要讀取最后一條命令的輸出,因此父neeed需要關閉所有其他管道末端。 子進程需要關閉stdin / stdout和dup2()管道描述符,以將它們綁定到stdin / stdout然后是exec()。 對於管道,關閉過程中不需要的管道末端非常重要。 參見http://linux.die.net/man/2/pipe

目前我還沒有一個Linux機器,所以我不能編寫和測試Linux代碼。

我為您提供的摘要是:-父級從最后一個管道讀取(鏈中最后一個進程的標准輸出)-所有其他子級需要close()他們的stdin / stdout,dup2()在正確的管道末端,關閉所有不需要的管道(記住也關閉dup2()源,因為它是fd)然后執行。

這是我如何創建管道並重新綁定fds的示例。

// unset FD_CLOEXEC
set_close_on_exec(to_child,false);
set_close_on_exec(from_child, false);

// close and rebind the stdin/stdout/stderr
// dup the fd and recreate stdin/stdout with fd as the target
if (dup2(to_child, STDIN_FILENO) != 0 || dup2(from_child, STDOUT_FILENO) != 1) {
    shared::perror("error duplicating socket for stdin/stdout");
    exit(EXIT_FAILURE);
}

// close these FDs
close(to_child);
close(from_child);

// now we can exec the new sub process and talk to it through
// stdin/stdout/stderr
execlp(exe.c_str(), exe.c_str(), argv.c_str(), (char*)0);

// this should never be reached
shared::perror("error: executing the binary: " + exe);
exit(EXIT_FAILURE);

請記住,在pipe(int fds [2])處,索引1是管道的寫端,索引0是管道的讀端。 所以你需要

問候喬治

編輯:我向您推薦《 Linux編程接口:Linux和UNIX系統編程手冊》一書ISBN-13:978-1593272203

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM