我在类似的情况下使用了 Boost Unit Test 库并获得了积极的结果。我想进行自动测试,看看库在分叉时是否正常工作。尽管在我的情况下它也更接近于系统测试,但如果它们实现了您想要的,我完全赞成使用可用的工具。
但是要克服的一个障碍是在不使用 boost 断言宏的情况下从子进程发出错误信号。如果使用 eg BOOST_REQUIRE
,它将过早中止测试,并且任何后续测试都将在父进程和子进程中执行。我最终使用进程退出代码向等待的父进程发出错误信号。但是,不要使用exit()
as boost 有atexit()
在子进程中发出错误信号的钩子,即使没有。改为使用_exit()
。
我用于测试的设置是这样的。
BOOST_AUTO_TEST_CASE(Foo)
{
int pid = fork();
BOOST_REQUIRE( pid >= 0 );
if( pid == 0 ) // child
{
// Don't use Boost assert macros here
// signal errors with exit code
// Don't use exit() since Boost test hooks
// and signal error in that case, use _exit instead.
int rv = something();
_exit(rv);
}else{ // parent
// OK to use boost assert macros in parent
BOOST_REQUIRE_EQUAL(0,0);
// Lastly wait for the child to exit
int childRv;
wait(&childRv);
BOOST_CHECK_EQUAL(childRv, 0);
}
}