2012-04-04 36 views
0

我有一個程序讀取一個文件,對待它並把結果放在一個輸出文件中。當我有一個參數(輸入文件)時,我創建輸出文件並將其寫入內容。execl不要離開孩子

我已經做了一個fork()爲了重定向標準輸出write()內容。

char *program; 

program = malloc(80); 

sprintf(program, "./program < %s > %s", inputFile, outputFile); 
int st; 
switch (fork()) { 
    case -1: 
     error("fork error"); 
     case 0: 
      /* I close the stdout */ 
      close (1); 

      if ((fd = open(outputfile, O_WRONLY | O_CREAT , S_IWUSR | S_IRUSR | S_IRGRP)==-1)){ 

       error("error creating the file \n"); 
       exit(1); 
      } 

      execlp("./program", program, (char *)0); 

      error("Error executing program\n"); 
       default: 
      // parent process - waits for child's end and ends 
      wait(&st); 
      exit(0); 
    //***************** 

       } 

孩子與<>標準輸入正確創建並創建標準輸出文件。 但是,孩子永遠不會結束,當我殺了父親,輸出文件是空的,所以代碼沒有執行。

發生了什麼事? 謝謝!

+0

我會做這與'開放()'和'DUP2()'和'EXEC()',而不是試圖用'<' and '>'爲IO重定向。 – Flexo 2012-04-04 16:38:46

+0

謝謝!兩種解決方案都有效 – drules 2012-04-04 17:25:29

回答

1

exec系列中的函數不理解重定向

您打電話給execlp的方式,您將一個參數傳遞給您的程序:./program < %s > %s。這是對的,有一個論點。當然,execlp不知道重定向是什麼,program也不知道。

我會取代所有的代碼:

char *program = malloc(LEN); 

snprintf(program, LEN, "./program < %s > %s", inputFile, outputFile); 
system(program); 
+0

我同意你的診斷,但我沒有在建議的解決方案上出售 - dup2似乎是一個更簡潔的方法。 – Flexo 2012-04-04 16:41:16

+0

@awoodland爲什麼更清潔?離開重定向到shell可能是最簡單的 - 這是shell的目的。當然,它不是很有效率,也不是便攜式的,而是由3條線組成。 – cnicutar 2012-04-04 16:42:07

+0

嵌套殼內東西深感到骯髒。除了時髦的shell的非優雅失敗(如果它會失敗,我寧願有一個編譯時錯誤比一個奇怪的運行時問題),它很容易受到邪惡的東西,例如,如果outputFile有一個'somepath; rm -rf〜',或者更糟。 – Flexo 2012-04-04 16:46:46