I have a program that reads a file, treat it and put the results in an output file. When I have an argument (input file), I create the output file and write it the content.
I’ve made a fork() in order to redirect the stdout a write() content.
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);
//*****************
}
The child is created properly with the < > stdin and stdout files are created.
But, the child never ends, and when I kill the father, the output file is empty, so the code did not executed.
What is happening?
Thanks!
The functions in the exec family don’t understand redirections.
The way you’re calling
execlp, you’re passing one argument to your program:./program < %s > %s. That’s right, one argument. Of course,execlpdoesn’t know what redirections are, and neither doesprogram.I would replace all your code with: