if (!fork) - what does it mean?

c, fork, unix

Solution

From the `fork(2)` manpage:

Return Value

On success, the PID of the child process is returned in the parent, and `0` is returned in the child. On failure, `-1` is returned in the parent, no child process is created, and `errno` is set appropriately.

Since `fork()` returns 0 to the child, the `if` clause tests if it's a child:

if (!fork()) // same as: if (fork() == 0)
{
  // child
}else{
  // parent
}

Problem

What does it mean `if(!fork())`? I'm a little bit confused about it, I dont know when Im in parent and child process: ``` if(!fork()) { // is it child or parent process? }else{ // is it child or parent process? } ```

Original source