How can I create a process in a portable manner?

房东的猫 提交于 2019-12-06 11:34:03

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!