我怎样才能创建一个可移植的方式的过程? [英] How can I create a process in a portable manner?

查看:100
本文介绍了我怎样才能创建一个可移植的方式的过程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个程序,需要创建一些其他进程。我已经习惯了Windows的API,但现在我需要我的程序能够在Linux平台上运行了。

I'm trying to write a program 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.

是否有可能做到在一个可移植的方式?我必须使用preprocessor用于这一目的?

Is it possible to do it in a portable manner? Do I have to use the preprocessor for that purpose?

编辑:我需要等待它继续做的事情前完成

推荐答案

在我看来任何时候都要避免系统功能:它是不可靠的,因为你不知道什么shell将处理您的指令,它没有办法回你一个明确的错误code。此外,在诸如Windows平台上,其中的过程是相当重量级它不是推出一个新的进程刚刚推出一个又​​一个,并且,顺便个不错的主意,一些安全套件可以发射用于每个应用程序尝试启动过程警告,加倍本通知(一个用于指令间preTER,一个用于实际推出的应用程序)可能会倍加骚扰用户。

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.

如果您只需要创建一个新的过程中,你可能只是创建一个围绕实际的特定于平台的code您的包装功能,当程序被编译多亏了preprocessor将被自动选择。事情是这样的:

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
}

顺便说一句,该功能可以很容易地扩展到会阻止,你可以简单地添加一个标志(INT阻塞,或任何在C99现用于布尔值)将触发WaitForSingleObject的对Win32部分和waitpid函数对于POSIX部分。

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.

这篇关于我怎样才能创建一个可移植的方式的过程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆