c - Understanding how fork() and wait() work together -
this isn't in code review because not understand full concept of code start with. if should still moved let me know.
i have code , explain thoughts on it, , hoping can tell me going wrong or getting confused @ because still not sure 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); // 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 understand, have 2 process id's, parent (pid) , child (pid1). once call pid = fork()
, believe child initiated , given id of 0, while parent get's id of child, let 1337. pid = 1337 , pid1 = 0.
so skip first if
no error has occurred (pid < 0), skip second if
since pid not equal 0, , enter final if
c print 1337 , d pint out 0.
this waits until child done, think.
after that, assume copied process (fork()) run else if (pid == 0)
confused on why, because pid still 1337..
tldr: if third if
should executing first, how second if
, if logic wrong please correct me.
a fork creates makes (near-perfect) copy of running process. 1 difference, surmised return value of fork()
itself. so, assuming fork works have 2 processes executing same code. one, child, takes if (pid == 0) ...
path, while parent takes else...
path. have no information order in 2 processes work. maybe child goes first, maybe parent, maybe half way through take turns, maybe have 2 processors , run together...
imagine have program written on piece of paper , following along finger, sliding down page. when fork, take paper copier, make copy, put both pieces of paper on table, put index finger each hand on 1 of pieces, move both fingers, each sliding down own sheet of paper.
Comments
Post a Comment