dgamma3
dgamma3

Reputation: 2371

understanding forking - simple

if I have a program like this:

int i = 0;
int status;
bool result = true;

    for(i = 0; i < numfiles; i++) { // LOOP 1
        if (fork() == 0) {/* Child */
            if (substLines(s1, s2, filenames[i])) {
                exit(0);
            } else {
                exit(2);
            }
        }
    }
    for(i = 0; i < numfiles; i++) { // LOOP 2
        wait(&status);
        ....
    }

    return result;
}

I have the following question.

  1. what happens if a child process exists, before the program even knows about the wait(). I guess my question is regarding how a program is 'read'. Again, for example. If I exit from the first child, whilst still going through LOOP 1, what happens (does it even know about LOOP 2 at this point)?
  2. is this a concurrent program? the parent seems to be waiting on the children after is forked them all, so i would say yes?

Upvotes: 0

Views: 75

Answers (2)

simon_xia
simon_xia

Reputation: 2544

The man page of wait says

If a child has already changed state, then these calls return immediately. Otherwise they block until either a child changes state or a signal handler interrupts the call

so question1 doesn't matter

and question2, the answer is no.

Concurrency means they are running at the same time. It needs mutil-core CPU or more than one computer such as distributed system.

your program is multi-process, it is just Parallelism, which means they are running one by one under the schedule of CPU, for more info: Scheduling_(computing)

Upvotes: 2

SzG
SzG

Reputation: 12609

Just an addition to @simon_xia's excellent answer.

A killed or exited process becomes a zombie until its parent calls wait for it. And yes, this is the official terminology. :-) In zombie state everything is cleaned up (memory pages, open files, env, etc), just the exit status or killing signal number are kept.

Upvotes: 0

Related Questions