after hours of searching I ended up here. Here's my problem:
I have an exercise I need to do.The code given is this:
int main(){
int x,y,z....;
//
fill the gap
//
printf("A");
//
fill the gap
//
printf("B");
return(0);
}
I must print exactly "AAAAABBB" with using ONLY fork(),if and exit(). (no "wait", no multiple "printf", no "sleep". no "for")
How could I do it? I have tested it in online IDEs but I just cant print them in this exact way. The output is always confusing (AABBBAA, ABABABAA etc.) I can't seem to understand how to give priority to the parent or child without using anything but fork() and if.
Any tip is appreciated.
What you are supposed to be learning here is that fork() duplicates your process - at the point of the fork(). It returns a Process IDentifier (PID) number to the parent process, and zero to the child process.
So by simply watching the return of the fork(), the execution path can determine if they are the parent or child process.
Thus to implement the problem, I took the approach of controlling everything from the single parent process, and having the child simply output a letter, then exit() - which terminates the process.
It would be much nicer with a for() loop, but that was not allowed.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int pid = fork();
if (pid != 0)
pid = fork();
if (pid != 0)
pid = fork();
if (pid != 0)
pid = fork();
if (pid != 0)
pid = fork();
if (pid == 0)
{
// child process only
printf("A");
exit(0);
}
pid = fork();
if (pid != 0)
pid = fork();
if (pid != 0)
pid = fork();
if (pid == 0)
{
// child process only
printf("B");
exit(0);
}
return 0;
}
Note: I suspect that it may occasionally get mixed up due to system load, scheduling, etc. But in all my tests I received the correct answer.