我有一个程序可以读取文件,对其进行处理并将结果放入输出文件中。当我有一个参数(输入文件)时,我创建输出文件并写入内容。
我创建了一个 fork() 以便将 stdout 重定向为 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);
//*****************
}
使用 < > stdin 和 stdout 文件正确创建子级。 但是, child 永远不会结束,当我杀死父亲时,输出文件是空的,因此代码没有执行。
发生了什么事? 谢谢!
最佳答案
exec 系列中的函数不理解重定向。
您的通话方式execlp
,您将一个参数传递给您的程序: ./program < %s > %s
。没错,一个论点。当然,execlp
不知道什么是重定向,program
也不知道。
我会将您的所有代码替换为:
char *program = malloc(LEN);
snprintf(program, LEN, "./program < %s > %s", inputFile, outputFile);
system(program);
关于c - execl 不要离开子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10015439/