2012-11-27 34 views
0

爲什麼在以下程序中字數輸出0 0 0?fork/Dup2/Exec不適用於mkstemp

int main(int argc, char **argv) { 
    pid_t pid = fork(); 
    const char *data = "THIS IS MY DATA."; 
if(pid == 0) { 
    // Child Process 
    char *tmpname = malloc(15); 
    strcpy(tmpname, "/tmp/datXXXXXX"); 
    int f = mkstemp(tmpname); 
    //int f = open("tmpfile", O_RDWR | O_CREAT, S_IRWXU); 
    if(f == -1) { 
     perror(""); 
     return; 
    } 
    int written = write(f, data, strlen(data)); 
    dup2(f, STDIN_FILENO); 
    close(f); 
    char *wcargs[5] = {"wc", NULL}; 
    execvp("wc", wcargs); 
    fprintf(stderr, "ERROR"); 
} 
return 1; 
} 
+0

你應該對你的'fork'調用進行錯誤檢查,並且你沒有調用'free'。 – squiguy

回答

1

嘗試在使用lseek(0,0,SEEK_SET)的dup2()之後倒退stdin。在你的代碼中,wc將試圖從文件尾部讀取,顯然不會有任何字節需要讀取。

相關問題