Today, I found an interesting piece of code while reading the code.
#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<sys/types.h>int main(){ int pid=1; if(pid=fork()<0) { perror("fork() error!\n"); exit(-1); } else if(pid==0) { printf("child pid[%d]\n",getpid()); sleep(15); } else { printf("parents pid[%d]\n",getpid()); sleep(15); } return 0;}
First, let's guess what the execution result of this code is?
It looks very simple. Many people say the results are as follows:
Child PID [% d]
Parents PID [% d]
The result is as follows:
Child PID [% d]
Child PID [% d]
If the code is changed to If (pid = fork () <0)
The results are as expected:
Child PID [% d]
Parents PID [% d]
The reason is the operator priority.
Because the priority of the operator '<' is higher than that of the operator '=. Therefore, the PID obtains the result of the comparison expression (Fork () <0 ). This result is false, so pid = 0. Therefore, both the parent and child processes output the child PID [% d].
Where fork is prone to errors