I'm trying to write a progra开发者_Go百科m which needs to create some other processes. I'm used to the Windows API but now I need my program to be able to run in a Linux platform too.
Is it possible to do it in a portable manner? Do I have to use the preprocessor for that purpose?
EDIT: I need to wait for it to finish before continuing to do things.
In my opinion the system function should always be avoided: it's unreliable, since you don't know what shell will handle your command and it doesn't have means to return you an unambiguous error code. Moreover, on platforms like Windows where processes are quite heavyweight it's not a good idea to launch a new process just to launch another one, and, by the way, some security suites may emit a warning for each process your app tries to launch, and doubling this notice (one for the command interpreter, one for the app actually launched) may doubly annoy the user.
If you just need to create a new process, you may just create your wrapper function around the actual platform-specific code, that will be selected automatically when the program will be compiled thanks to the preprocessor. Something like this:
int CreateProcess(const char * Executable, const char * CommandLine)
{
#if defined (_WIN32)
return CreateProcess(Executable, CommandLine /* blah blah blah */)!=FALSE;
#elif defined (_POSIX)
/* put here all the usual fork+exec stuff */
#else
#error The CreateProcess function is not defined for the current platform.
#endif
}
By the way, the function can be expanded easily to be blocking, you may simply add a flag (int Blocking, or whatever is now used in C99 for the booleans) that will trigger a WaitForSingleObject for the win32 section and a waitpid for the POSIX section.
The APIs are different, so there's no way around either writing two pieces of code or linking to a library which does the same.
The Apache Portable Runtime is a good option for writing portable low-level programs in C.
How much control over the other threads do you need? If it is a simple matter of just starting them, then the system()
function is probably a good fit. If you want more control over them, I'd look into a library. I know that Qt makes it fairly easy to do some aspects of multi-process programming.
Try system() as it exists on both Posix and Windows.
@Jeff - system() is a blocking call, it will not return until the child process exits.
精彩评论