I am writing a program that will eventually be used to have one child process send randomly generated characters through a pipe to another child process to convert to uppercase values and output, but before I get that far, I am trying to create the child processes and make some expected output. I have written the following application:
#include <stdio.h> /* printf, stderr, fprintf */
#include <sys/types.h> /* pid_t */
#include <unistd.h> /* fork */
#include <stdlib.h> /* _exit */
#include <errno.h> /* errno */
int main()
{
pid_t writer;
pid_t reader;
writer = fork();
if (writer == -1)
{
fprintf(stderr, "can't fork, error %d\n", errno);
exit(1);
}
if (writer == 0)
{
printf("Writer process created.\n");
reader = fork();
if (reader == -1)
{
fprintf(stderr, "can't fork, error %d\n", errno);
exit(1);
}
if (reader == 0)
{
printf("Reader process created.\n");
kill(reader);
printf("Reader was successfully murdered.\n");
}
kill(writer);
}
wait();
printf("Writer killed.\n");
return 0;
}
I would ideally like the output to come out as the following:
Writer process created.
Reader process created.
Reader was successfully murdered.
Writer killed.
But as of this point, it outputs:
Writer process created.
Reader process created.
Reader was successfully murdered.
Writer killed.
Writer killed.
Writer killed.
It is as if it is going through the entire iteration of the code for the parent process, and two child processes from the point that they are created, which also leads me to believe that they are not being killed at the appropriate time that I want them to. Could someone point me in the right direction?
Here is your full working example with pipes (they also synchronize processes, so you do not have to kill them). Bear in mind that reader process is reading very inefficiently (by one character – I’ll leave it as an exercise to you :))
Result: