tags:

views:

62

answers:

1

On a Gnu system, I can write a C macro like dies_ok() that will fork a new process, run a piece of code, after which it can write to a shared piece of memory that it didn't exit, then in the parent process I can determine if it exited or not. This is useful for tests:

dies_ok({int x = 0/0;}, "can't divide by zero");
lives_ok({int x = 3/7;}, "this is a perfectly fine statement");
dies_ok({abort();}, "abort kills the program");

Is there any way to accomplish this on MSVC where there isn't a fork function?

EDIT: Heres the implementation that works on linux with gcc: http://github.com/zorgnax/libtap/blob/master/tap.h

+1  A: 

CreateProcess is like fork()/exec()

The BOOST library has shared memory support for msvc. You can also use the Windows atom table which is native to Windows- see msdn for

http://msdn.microsoft.com/en-us/library/ms649053(VS.85).aspx

Q: I don't get why in unix you have to write a string to shared memory. You can simply call exit(n) from the child process where n is an index into a predefined char *p[] list of error codes or success codes. You can have an array of 255 values, excluding 0 for EXIT_SUCCESS. Or read the sysexits.h header file for another set of ideas. wait() or waitpid() will return the exit code, or determine if the process did not exit

jim mcnamara
I need to use shared memory because I cant rely on any specific exit value. I want to know whether it exits, aborts, or crashes, not its exit code. Anyway, I think the windows builtin, CreateFileMapping() function will be able to do something similar to a mmap(). CreateProcess() doesn't seem powerful enough for me since it requires an executable name. I only have a few lines of code.
Jake
Well, all of that is available via WIEXITED, WIFSIGNALED, WCOREDUMP, etc as an argument to waitpid().
jim mcnamara
The child process is going to exit regardless of whether the code im testing did it or I did it after that code finishes. The main issue is making the code execute in place, I cant create a new function and I definitely cant create a new program. I'm trying to work it into this a macro like dies_ok({int x = 0/0;}, "can't divide by zero"); and hopefully not have to change that.
Jake
@Jake: A process that aborts or crashes will never exit with a 0 code, so you can definitely treat zero exit status as a successful test.
caf