I have some C code which uses fork()+exec(), wait() (or waitpid()) and kill() - and assumes they exist after including the relevant POSIX headers.
Now, I want to make this code as multi-platform as possible - with minimal changes. So, no introduction of third-party library dependencies, and no implementing these facilities on systems that don't have them. However, it is important for me to go beyond just Linux, Windows and Mac OS. My tool for doing so is CMake, which the project with this code uses; and the C preprocessor. Maybe a smidgen bit of glue code in C proper.
My question: What should I check for, what should I put in a generated include file, and how should I modify my code calling these functions to effect the same behavior on both POSIX and various non-POSIX platforms?
PS - I realize many platforms don't have Unix-style signals. Let's assume for the sake of discussion I'm only terminating processes, not sending other signals.
Windows
Well
fork()(create a new process) andexec()(run a new program in this process) don't exist on Windows, plain and simple. Instead, you haveCreateProcesswhich combines the two.You can then use
TerminateProcessto, well, terminate a process.You could then implement two separate
.cfiles: one for Windows, and one for systems that havefork()/exec().POSIX
If you only care about portability across POSIX environments (Linux, BSD, Mac OS), then
posix_spawn()is definitely the way to go. It handles all the intricacies of error handling in the child process.See also: capability of `posix_spawn`
Cross-platform Libraries
There are a number of cross-platform frameworks that solve this problem for you:
They of course solve a number of other portability problems also, so it's best to really "buy in" and use the framework for everything you do that interacts with the system.