Unix Fork奇怪的行为

时间:2015-09-28 02:08:55

标签: c unix fork

#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);
}

您好,我无法理解上述代码的工作原理...... 当执行上面的代码时,我得到输出:

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

这非常令人沮丧,因为我期待以下输出:

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...

这很令人沮丧,因为看来叉子之后, 原来的duplifork功能完美无缺。 但是,它的副本,它调用另一个函数, 并需要返回值才能继续执行, 从来没有真正表现那样。 有人可以向我解释实际上是什么 去吧?提前谢谢。

1 个答案:

答案 0 :(得分:1)

您的函数指针语法错误。

int *func(void*)

应该是:

int (*func)(void*)

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

应该是:

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

进行这些更改,你会得到类似的东西:

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$ 

因为您(也可能错误地)除父母之外还有子进程wait()