I was given this code and asked to list how many processes it creates and some possible outputs of the code. I have no idea how these forks work and do not understand the outcome I’m getting when I run the code. I get that when fork is called it creates a child process but I’m wondering if someone can walk me through how this code actually works.
int main() {
int pid;
printf(‘‘Jingle Bells!n’’);
pid = fork();
if (pid == 0) {
printf(‘‘Oh what funn’’);
pid = fork();
}
else {
printf(‘‘ it is to riden’’);
}
if (pid != 0) {
printf(‘‘ in a one-horse open sleighn’’);
}
pid = fork();
printf(‘‘Jingle Bells!n’’);
return 0;
}
I ran the code and got output like
“Jingle Bells!
it is to ride
Oh what fun
in a one-horse open sleigh
in a one-horse open sleigh
Jingle Bells!
Jingle Bells!
Jingle Bells!
Jingle Bells!
Jingle Bells!
Jingle Bells!” and I have no idea how or why “Jingle Bells” is printed that many times.
Emma Markle is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.