Confused about fork function

This is the code I'm confused with.

#include "csapp.h"
void doit()
{
    if ((fork) == 0) {
            fork();
            printf("hello\n");
            return;
    }
    return;
}

int main()
{
    doit();
    printf("hello\n");
    exit(0);
 }

I run this program on MAC,I got only one hello printed.I think there should be 5 lines of 'hello',because the child process return to their parent and print one 'hello' each.

Can anybody give me an answer? Thanks a lot!!

Answers


You didn't call fork() and you just compared its address with 0, which ls a null pointer constant.

(fork) == 0 has too little chance to become true, so what is inside the block after the if statement won't be executed.

Call fork() to create a child process.

Try this:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void doit(void)
{
    if (fork() == 0) {
        fork();
        printf("hello\n");
        return;
    }
    return;
}

int main(void)
{
    doit();
    printf("hello\n");
    exit(0);
}

Need Your Help

Does anyone have INFORMIX-SQL 4.10DC1 or DD6 for MS-DOS?

informix dos

If you do, I'm looking for documentation pertaining to installation settings and DOS protected mode troubleshooting. I'm getting a DOS/16M: Error [6] Not enough memory to load PSTARTSQL.EXE (protec...

Can I access an xcassets directory on the filesystem?

ios xcode cocoa-touch asset-catalog xcasset

I would like to dynamically load all images in an xcassets directory. The files are named StockPhoto# where # is the number in the list. If I can access my StockPhotos.xcassets at runtime to count ...