在fork()和wait()之后从exit()获取错误的返回码

时间:2012-09-07 05:03:31

标签: c fork wait

我正在为我的小守护进程进行单元测试,但是我无法从分叉进程中获取正确的退出代码。如果我只运行其中一个测试用例,它们可以正常工作,但如果我连续运行两个,则第二个失败,因为它没有获得EXIT_SUCCESS作为返回码。我已经检查过,第二个测试用例确实调用了exit(EXIT_SUCCESS),所以它应该返回,但不知怎的,我得到另一个子进程。

我错过了什么?

bool test_setup() {
    pid_t pid = fork();
    if(pid < 0) {
        fail("Failed to fork", PLACE);
    }
    else if(pid > 0) { //main thread
        //act as client to server, this code might call exit(EXIT_FAILURE)
        exit(EXIT_SUCCESS);
    }
    //child thread
    //run server
    int retval; //return value from child process
    wait(&retval);
    return WEXITSTATUS(retval) == EXIT_SUCCESS;
}

bool test_send_one() {
    pid_t pid = fork();
    if(pid < 0) {
        fail("Failed to fork", PLACE);
    }
    else if(pid > 0) { //main thread
        //act as client to server, this code might call exit(EXIT_FAILURE)
        cout <<"exit success" <<endl;
        exit(EXIT_SUCCESS);
    }
    //child thread
    //run server
    int retval; //return value from child process
    wait(&retval);
    return WEXITSTATUS(retval) == EXIT_SUCCESS;
}

int main(int argc, char** argv) {
    test_setup();   
    test_send_one();
}

1 个答案:

答案 0 :(得分:0)

我交换了if(pid&gt; 0)和if(pid == 0)。