fork(), could you explain!!

Dear friends,
We are learning UNIX system programming as part of our course. I came across this simple program, which the teacher didn't explain well enough. could you please explain this program fully

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int pid;
int status = 0;
if(pid = fork())
{
pid = wait(&status);
printf("%d\n",pid);
}
else
{
exit(status);
}
return 0;
}

And why does this program give an output of 912???
Thanks

When fork() is invoked the system creates a new process which is nearly an exact copy of the process invoking the function. The new process begins execution of the same binary (programme) starting with the statement immediately following the fork().

So, following the fork(), the programme that you posted is being executed in two different processes. The most noticeable difference is that in the parent process, the process that invoked fork(), the return value is the process id (PID) of the newly created process; in the child, the return value is zero.

Given that, the statement

if( pid = fork() )

will evaluate 'true' in the parent and 'false' in the child. That means, the parent will execute the wait() call to wait on the child to finish execution. In the case of your example, the child will just exit with a zero (good) return code.

The return from the wait() function is the process ID of the process that finished. If the parent forks off more than one, knowing which one finished might be important. In your sample programme, the PID of the child is what is printed to stdout. If you run the process two times in a row it shouldn't print the same thing.

Hope this helps a bit.

Your program is calling printf(("%d\n",pid) from only one location (and from the if() block where its testing for the value of pid only after the expression pid = fork() is evaluated); so no mixture output, a simplest case of such fork() examples.

Who is executing that if() block ???. Its the parent (remind that fork() is a system call returns two times after a single call to it and it returns the parent (the callee to fork()) with the process id of the child it just created and a zero to that child. Hence that if() block is being executed by the parent only and its printing the process id it had received and collected in the variable pid of your program.

The output is just the process id of the child process created.