For an assignment, I'm supposed to create four processes in total, and print a letter multiple with each process. I'm supposed to call fork()
twice to accomplish this.
I've been able to print the letters multiple times for each process. The problem arises in the second part of the assignment details. I'm supposed to print out the process ID for each process running before I print out the letters. The output should look like this:
Process ID: 123
Process ID: 124
Process ID: 125
Process ID: 126
AAAAABBBBBCCCCCDDDDD
I thought this could be accomplished by using this code:
pid_t child1, child2;
child1 = fork();
child2 = fork();
printf("Process created. ID: %d\n", getpid());
if(child1 == 0) { // print letters }
else if(child2 == 0) { //print letters }
else { // call waitpid and print more letters }
I thought since fork()
splits at line child1 = fork()
, then splits again at child2 = fork()
, then goes to the next line, it would print everything out then hit the if-else
statements. However, this is my output:
Process created. ID: 20105
Process created. ID: 20107
AAProcess created. ID: 20106
AAABBBProcess created. ID: 20108
BBCCCCCDDDDD
How can I ensure that my Process Created print statements execute first?