2009-12-31 54 views
0

我必須捕獲程序中的stdout並將其寫入文件中...所以我創建了一個管道。在父進程中,我使用dup()捕獲了管道中的stdout,並且我需要將它存入一個文件中...所以我在子進程中做了一個dup()以獲取捕獲的文件描述符到stdin中。現在,我如何使用fwrite()將此stdin寫入文件?使用fwrite將stdin寫入文件()

回答

0

你應該捕獲到一個字節或字符緩衝區和fwrite的發送。 當我說一個緩衝區時,我的意思是一個數組或動態分配的字節/字符塊。

2

難道不是這樣做嗎?您需要在父項中執行的操作是使用freopen()將stdout連接到您選擇的文件。

FILE *fp = freopen("/tmp/mylogfile", "w", stdout); 

if (fp == 0) 
    error("...something went wrong opening the log file...\n"); 

直接回答你的問題是:

char buffer[32768]; 
ssize_t nbytes; 
FILE *fp = fopen("/tmp/mylogfile", "w"); 

if (fp == 0) 
    error("....something went wrong opening my log file...\n"); 

while ((nbytes = fread(buffer, sizeof(char), sizeof(buffer), stdin)) > 0) 
    if (fwrite(buffer, sizeof(char), nbytes, fp) != nbytes) 
     error("...something went wrong writing to standard output...\n"); 

然而,這是沒有什麼必要。您可以通過各種方式改進錯誤處理;我簡單地假設'error()'報告消息,並且不返回

+0

是的,可是這只是一個學習C方式...我努力去學習使用管道。 – sfactor 2009-12-31 05:38:45

+0

好的 - 這樣做不會有什麼壞處;它爲做事情找藉口不合適的技巧。我已經給出了直接的答案。但是,如果我使用管道作爲管道,而不是巧合地使用碰巧連接到管道的文件流,我會使用文件描述符I/O調用(例如read()和write()),而不是文件流I/O調用如fread()和fwrite()。 – 2009-12-31 05:42:52

+0

使用管道(尤其是使用dup()時要記住的主要問題是關閉管道未使用的端點。如果你不這樣做,事情不會正確終止。 – 2009-12-31 06:49:53

1

最簡單的方法就是打開文件和規定,在有孩子的stdout:

#include <fcntl.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <sys/wait.h> 
#include <unistd.h> 

#include <stdio.h> 

int main() { 
    pid_t pid = fork(); 
    switch (pid) { 
    case -1: 
    perror("fork"); 
    return 1; 

    case 0:; 
    int new_out = open("output.txt", O_WRONLY | O_CREAT, 0666); 
    if (new_out == -1) { 
     perror("open"); 
     return 1; 
    } 
    if (dup2(new_out, 1) == -1) { 
     perror("dup2"); 
     return 1; 
    } 
    char* args[] = {"/bin/echo", "test output", 0}; 
    execv(args[0], args); 
    perror("exec"); 
    return 1; 

    default:; 
    int s; 
    if (waitpid(pid, &s, 0) == -1) { 
     perror("waitpid"); 
     return 1; 
    } 
    if (WIFEXITED(s)) { 
     return WEXITSTATUS(s); 
    } 
    return 1; 
    } 
}