I am unable to redirect STDOUT to a file.
I have two processes. These should run for 5 seconds and then be killed.
Process 1: redirects its STDOUT to a pipe and then prints random nubers.
Process 2: redirects its STDIN to the pipe and its STDOUT to file. Then it calls procedure appc1 by execl(). This procedure prints to STDOUT.
Problem: File out.txt contains the test print done by reader process, but nothing else from the appc1 procedure. If I skip the redirection and print to console, everything works fine.
Could it be an issue caused by killing the processes? Do I close the file too soon? Thank you very much for any advice, I am unable to solve this for quite some time.
ret = pipe(pipefd);
if (ret == -1) {
printf("Error creating pipe");
exit(1);
}
reader = fork();
if (reader == 0) {
dup2(pipefd[0], STDIN_FILENO);
file = fopen("out.txt", "w");
if(file == NULL) fputs("Could not open file",stderr);
dup2(fileno(file), STDOUT_FILENO);
fclose(file);
printf("Test values: %d %d\n\n", 234, 598);
execl("appc1","appc1", NULL);
}
else {
printf("PARENT: forking writer\n");
writer = fork();
if (writer == 0) {
sleep(1);
dup2(pipefd[1], STDOUT_FILENO);
while (1) {
num1 = rand() % 1000 + 1;
num2 = rand() % 1000 + 1;
printf("%d %d\n", num1, num2);
sleep(1);
}
}
else {
sleep(5);
kill(reader, SIGUSR1);
kill(writer, SIGUSR1);
wait(NULL);
exit(0);
}
}
This is the code.
Thank you guys.