我有一个程序读取一个文件,对待它并把结果放在一个输出文件中。当我有一个参数(输入文件)时,我创建输出文件并将其写入内容。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