-1

我正在为我的小守护进程进行单元测试,但我无法从分叉进程中获取正确的退出代码。如果我只运行其中一个测试用例,它们可以正常工作,但如果我连续运行两个测试用例,第二个测试用例会失败,因为它没有获得 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();
}
4

1 回答 1

0

我交换了 if(pid > 0) 和 if(pid == 0)。

于 2012-09-26T10:14:26.373 回答