2
votes

I have this program

childpid = 0;
int i, n;

for(i=1; i < n; i++)
    if((childpid = fork())
        break;
fprintf(stderr, "i:%d process ID: %ld parent ID: %ld child ID: %ld\n,
        i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;

It says that since a parent's process's childpid variable does not have a value of 0, it will break out of a loop. A a child process's pid is 0, and will become a parent in the next iteration.

To my knowledge, a new process is created with the code after the line fork() has been called. If a parent process breaks out of the loop as its childpid is not 0, does that not mean that the printf statement will be run once and the program will terminate since the loop has ended? I am confused about how this program runs.

I also have this code

for(i=1; i < n; i++)
    if( ((childpid = fork()) <= 0)
        break;
fprintf(stderr, "i:%d process ID: %ld parent ID: %ld child ID: %ld\n,
        i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;

This creates a fan of processes and does the opposite of the first program. The child process breaks out of the loop since its chilpid is equal to 0, and the parent processes run in the loop.

I have an exam on Monday, and I've understood everything else please do help :/

2

2 Answers

1
votes

does that not mean that the printf statement will be run once and the program will terminate since the loop has ended?

Yes it will. But not before it has spawned a child process to carry on its legacy.

Here's a poorly drawn diagram of what's going on. In code snippet #1, the process forks itself, the parent dies, and then the child keeps going in its place.

In code snippet #2, the process forks itself, the child dies, then the parent keeps going.

In each case, the result is a long sequence of print statements.

Crappy diagram showing process trees in each case

0
votes

I edited your first code a bit, and added "{ }" at the beginning and end of the if statement and for loop:

**int main()
{
int childpid = 0;
int i, n;
n=5;
for(i=1; i < n; i++){
    if((childpid == fork()))
    {
        break;
    }
        fprintf(stderr, "i:%d process ID: %ld parent ID: %ld child ID: %ld\n",
        i, (long)getpid(), (long)getppid(), (long)childpid);
    }
wait(0);
return 0;
}**

And this was the result:

i:1 process ID: 3443 parent ID: 2790 child ID: 0

i:2 process ID: 3443 parent ID: 2790 child ID: 0

i:3 process ID: 3443 parent ID: 2790 child ID: 0

i:4 process ID: 3443 parent ID: 2790 child ID: 0

What happens is that the main process( the parent) does all the prints in the for loop, while each child process exits right after the if statement.

While on your second code, instead of

if( ((childpid = fork()) <= 0) break;

you could write:

int f=fork();
if (f<0)
{
    perror("can't create child\n");
}

if(f==0)
{
    break;
}

Because if "f" is less than 0, it means that the child was not created successfully, if it was, it breaks out imediatley.