Currently, I am doing some exercises on operating system based on UNIX. I have used the fork() system call to create a child process and the code snippet is as follows :
if(!fork())
{
printf("I am parent process.\n");
}
else
printf("I am child process.\n");
And this program first executes the child process and then parent process.
But, when I replace if(!fork()) by if(fork()!=0) then the parent block and then child block executes.Here my question is – does the result should be the same in both cases or there is some reason behind this? Thanks in advance!!
if(!fork())andif(fork()!=0)do give opposite results logically: iffork()returns zero, then!fork()is true whilstfork()!=0is false.Also, from the man page for fork():
So the correct check is
EDIT: As Wyzard says, you should definitely make sure you make use of pid later as well. (Also, fixed the type to be pid_t instead of int.)