0

Hello I am having hard time understanding below code - I tried to break it down and understand it but still no luck -

/* Below code prints 20 times printf */

int main()
{
    if (fork() && fork())
    {
        fork();
    }

    if (fork() || fork())
    {
        fork();
    }

    printf("hello world\n");

    return 0;
}

/* If I break and just print AND part - it prints 4 hello world - which kind of makes sense if I assume with AND operation only 1 fork got executed */

int main()
{
    if (fork() && fork())
    {
        fork();
    }

    printf("hello world\n");

    return 0;
}

/* how is the OR operation working - prints 5 Hello World ??*/

int main()
{
    if (fork() || fork())
    {
        fork();
    }

    printf("hello world\n");

    return 0;
}

I have gone through below references from SO site too but still couldnt figure this one out

Understanding the fork() command Posix API

Working of fork() in linux gcc

Community
  • 1
  • 1
oneday
  • 629
  • 1
  • 9
  • 32
  • 3
    Hints: 1. If it's the child process `0` (false) is returned. 2. `&&` and `||` are short-circuit operators. – cadaniluk Sep 12 '15 at 17:31
  • `||` is short-circuiting, similarly to `&&`. If the first argument of `||` is nonzero, it won't evaluate the second one. – The Paramagnetic Croissant Sep 12 '15 at 17:31
  • @TheParamagneticCroissant - Yes I did think about it - but in that case if I just take example of || operation - wouldnt it result in 4 printf ? starts with main .. then from condition of if 1 fork and then 2 fork inside braces ? – oneday Sep 12 '15 at 17:34
  • 2
    It this to torture students?-S – alk Sep 12 '15 at 17:34
  • As alluded to earlier, and assuming no errors, the return value from fork() is zero in the child process but is non-zero in the parent process (in this case it's the process ID of the child process). – jarmod Sep 12 '15 at 17:37
  • @TheParamagneticCroissant - thanks for the link - that helps me understand the problem - should have searched harder - – oneday Sep 12 '15 at 17:44

0 Answers0