Frustrated Soul
Frustrated Soul

Reputation: 361

Unix Fork Strange Behavior

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int function(void* dat){
    sleep(5);
    printf("Executed Child Process...\n");
    return 5;
}

void dupliFork(int *childpid, int *funcRet, int *func(void*), void* data){
    int id = fork();
    if(id==0) *funcRet = *func(data);
    else *childpid=id;
    printf("Returned dupliFork with id %d\n", id);
}

int main(void){
    int childpid=0, funcRet=0;
    dupliFork(&childpid, &funcRet, function, NULL);
    printf("Waiting for Child Process with id %d...\n", childpid);
    waitpid(childpid, NULL, 0);
    printf("Child Process Terminated with return value %d...\n", funcRet);
}

Hello, I'm having trouble understanding how the above code works... When the code above is executed, I'm getting the output:

Returned dupliFork with id 4941
Waiting for Child Process with id 4941...
Executed Child Process...
Child Process Terminated with return value 0..."

This is very frustrating, as I was expecting the following output:

Returned dupliFork with id 4941
Waiting for Child Process with id 4941...
Executed Child Process...
Returned dupliFork with id 0
Child Process Terminated with return value 5...

This is frustrating because it seems that after the fork, the original duplifork function works perfectly. However, the copy of it, which calls another function, and needs the return value to continue its execution, never actually behaves that way. Could someone please explain to me what is actually going on here? Thank you in advance.

Upvotes: 0

Views: 85

Answers (1)

Crowman
Crowman

Reputation: 25936

Your function pointer syntax is wrong.

int *func(void*)

should be:

int (*func)(void*)

and:

if(id==0) *funcRet = *func(data);

should be:

if(id==0) *funcRet = func(data);

Make those changes, and you'll get something resembling:

paul@horus:~/src/sandbox$ ./fork
Returned dupliFork with id 69707
Waiting for Child Process with id 69707...
Executed Child Process...
Returned dupliFork with id 0
Waiting for Child Process with id 0...
Child Process Terminated with return value 5...
Child Process Terminated with return value 0...
paul@horus:~/src/sandbox$ 

since you also (probably erroneously) have the child process wait() in addition to the parent.

Upvotes: 1

Related Questions