2013-11-25 91 views
2

我幾乎不能理解pipe的手冊頁,所以我需要幫助理解如何在外部可執行文件中使用管道輸入。C Pipe到另一個程序的STDIN

我有2種方案:main.o & log.o

我寫main.o到餐桌。下面是它在做什麼:

  • 家長叉數據給孩子
  • 兒童叉EXEClog.o

我需要的兒童叉主要管到STDIN的log.o

log.o只需將帶有時間戳的STDIN &日誌記錄到文件中。

我的代碼是由來自不同的StackOverflow頁一些代碼,我不記得&管道手冊頁:

printf("\n> "); 
while(fgets(input, MAXINPUTLINE, stdin)){ 
    char buf; 
    int fd[2], num, status; 
    if(pipe(fd)){ 
     perror("Pipe broke, dood"); 
     return 111; 
    } 
    switch(fork()){ 
    case -1: 
     perror("Fork is sad fais"); 
     return 111; 

    case 0: // Child 
     close(fd[1]); // Close unused write end 
     while (read(fd[0], &buf, 1) > 0) write(STDOUT_FILENO, &buf, 1); 

     write(STDOUT_FILENO, "\n", 1); 
     close(fd[0]); 
     execlp("./log", "log", "log.txt", 0); // This is where I am confused 
     _exit(EXIT_FAILURE); 

    default: // Parent 
     data=stuff_happens_here(); 
     close(fd[0]); // Close unused read end 
     write(fd[1], data, strlen(data)); 
     close(fd[1]); // Reader will see EOF 
     wait(NULL); // Wait for child 
    } 
    printf("\n> "); 
} 

回答

4

我想這是你會怎麼做:
1.主叉,通過管道向父級傳遞消息。
2.孩子從管道接收消息,將消息重定向到STDIN,執行日誌。
3.從STDIN接收日誌消息,做一些事情。

要做到這一點的關鍵是dup2重定向文件描述符,從管道到STDIN。

這是修改後的簡版:

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

int main(int argc, char *argv[]) { 
    int fd[2]; 
    char buf[] = "HELLO WORLD!"; 
    if(pipe(fd)){ 
     perror("pipe"); 
     return -1; 
    } 
    switch(fork()){ 
     case -1: 
      perror("fork"); 
      return -1; 
     case 0: 
      // child 
      close(fd[1]); 
      dup2(fd[0], STDIN_FILENO); 
      close(fd[0]); 
      execl("./log", NULL); 
     default: 
      // parent 
      close(fd[0]); 
      write(fd[1], buf, sizeof(buf)); 
      close(fd[1]); 
      wait(NULL); 
    } 
    printf("END~\n"); 
    return 0; 
} 
4

我可以提出一個更簡單的方法。有一個叫popen()的功能。它的功能與system()功能非常相似,除了您可以讀取或寫入子女stdin/stdout

例子:

int main(int argc, char* argv[]) 
{ 
    FILE* fChild = popen("logApp.exe", "wb"); // the logger app is another application 
    if (NULL == fChild) return -1; 

    fprintf(fChild, "Hello world!\n"); 

    pclose(fChild); 
} 

寫 「人popen方法」 在控制檯的完整描述。

相關問題