This isn't in code review because I do not understand the full concept of the code to start with. If it should still be moved just let me know.
I have some code and I would like to explain my thoughts on it, and I am hoping someone can tell me where I am going wrong or getting confused at because I am still not fully sure what is occurring.
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid, pid1;
pid = fork();
if (pid < 0) {
fprintf (stderr, “fork() failed\n”);
return(1);
}
else if (pid == 0) {
pid1 = getpid();
printf (“pid = %d\n”, pid); // A
printf (“pid1 = %d\n”, pid1); // B
}
else {
pid1 = getpid();
printf (“pid = %d\n”, pid); // C
printf (“pid1 = %d\n”, pid1); // D
wait (NULL);
}
return 0;
}
From what I understand, we have two process ID's, the parent (pid) and the child (pid1).
Once I call pid = fork()
, I believe that the child is initiated and is given the id of 0, while the parent get's the ID of the child, let say 1337. So pid = 1337 and pid1 = 0.
So we skip the first if
as no error has occurred (pid < 0), we skip the second if
as well since pid does not equal 0, and then we enter the final if
where C will print 1337 and D will pint out 0.
This then waits until the child is done, I think.
After that, I assume that the copied process (fork()) will then run the else if (pid == 0)
but I am confused on why, because the pid is still 1337..
TLDR: If the third if
should be executing first, then how do I get to the second if
, but if this logic is all wrong please correct me.