Where fork is prone to errors

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.