我有一個程序讀取一個文件,對待它並把結果放在一個輸出文件中。當我有一個參數(輸入文件)時,我創建輸出文件並將其寫入內容。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);
//*****************
}
孩子與<>標準輸入正確創建並創建標準輸出文件。 但是,孩子永遠不會結束,當我殺了父親,輸出文件是空的,所以代碼沒有執行。
發生了什麼事? 謝謝!
我會做這與'開放()'和'DUP2()'和'EXEC()',而不是試圖用'<' and '>'爲IO重定向。 – Flexo 2012-04-04 16:38:46
謝謝!兩種解決方案都有效 – drules 2012-04-04 17:25:29