Linux 如何运行外部程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9550488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:58:54  来源:igfitidea点击:

How do I run an external program?

c++linux

提问by user

I'm on Linux mint 12.

我在 Linux mint 12 上。

I want to run a program usr/share/application/firefoxand then pass a string anywhere. I haven't found a solution for Linux but from what I've seen so far, there are many theories for Windows.

我想运行一个程序usr/share/application/firefox,然后在任何地方传递一个字符串。我还没有找到适用于 Linux 的解决方案,但据我目前所见,有许多适用于 Windows 的理论。

size_t ExecuteProcess(std::wstring FullPathToExe, std::wstring Parameters, size_t SecondsToWait) 
{ 
    size_t iMyCounter = 0, iReturnVal = 0, iPos = 0; 
    DWORD dwExitCode = 0; 
    std::wstring sTempStr = L""; 

    /* - NOTE - You should check here to see if the exe even exists */ 

    /* Add a space to the beginning of the Parameters */ 
    if (Parameters.size() != 0) 
    { 
        if (Parameters[0] != L' ') 
        { 
            Parameters.insert(0,L" "); 
        } 
    } 

    /* The first parameter needs to be the exe itself */ 
    sTempStr = FullPathToExe; 
    iPos = sTempStr.find_last_of(L"\"); 
    sTempStr.erase(0, iPos +1); 
    Parameters = sTempStr.append(Parameters); 

     /* CreateProcessW can modify Parameters thus we allocate needed memory */ 
    wchar_t * pwszParam = new wchar_t[Parameters.size() + 1]; 
    if (pwszParam == 0) 
    { 
        return 1; 
    } 
    const wchar_t* pchrTemp = Parameters.c_str(); 
    wcscpy_s(pwszParam, Parameters.size() + 1, pchrTemp); 

    /* CreateProcess API initialization */ 
    STARTUPINFOW siStartupInfo; 
    PROCESS_INFORMATION piProcessInfo; 
    memset(&siStartupInfo, 0, sizeof(siStartupInfo)); 
    memset(&piProcessInfo, 0, sizeof(piProcessInfo)); 
    siStartupInfo.cb = sizeof(siStartupInfo); 

    if (CreateProcessW(const_cast<LPCWSTR>(FullPathToExe.c_str()), 
                            pwszParam, 0, 0, false, 
                            CREATE_DEFAULT_ERROR_MODE, 0, 0, 
                            &siStartupInfo, &piProcessInfo) != false) 
    { 
         /* Watch the process. */ 
        dwExitCode = WaitForSingleObject(piProcessInfo.hProcess, (SecondsToWait * 1000)); 
    } 
    else 
    { 
        /* CreateProcess failed */ 
        iReturnVal = GetLastError(); 
    } 

    /* Free memory */ 
    delete[]pwszParam; 
    pwszParam = 0; 

    /* Release handles */ 
    CloseHandle(piProcessInfo.hProcess); 
    CloseHandle(piProcessInfo.hThread); 

    return iReturnVal; 
} 

You can see many theories herethe first answer describes how to get it done for Linux with C, I want to do it with C++, I've been googling for hours and i saw many theories. This subject appears to have more theories than quantum physics :)

你可以在这里看到很多理论第一个答案描述了如何用 C 为 Linux 完成它,我想用 C++ 来做,我已经用谷歌搜索了几个小时,我看到了很多理论。这个学科似乎比量子物理学有更多的理论:)

I am a Python guy, because I like simplicity, so please give a simple code that would work on 32 and 64 bit if possible.

我是一个 Python 人,因为我喜欢简单,所以如果可能的话,请给出一个可以在 32 位和 64 位上运行的简单代码。

I would like to do something like if usr/share/application/firefoxis available, run it, else run usr/share/application/googlechrome

我想做一些事情,如果usr/share/application/firefox可用,运行它,否则运行usr/share/application/googlechrome

And would you please tell me why can't the same code run on Mac and Windows?

你能告诉我为什么相同的代码不能在 Mac 和 Windows 上运行吗?

采纳答案by Appleman1234

This can be done using either systemwhich is the same as calling os.systemin Python or forkand execlor popenwhich is similar to calling subprocess.Popenin Python.

这可以使用systemos.system在 Python 中调用相同的方法或forkexeclpopen类似于subprocess.Popen在 Python 中调用的方法来完成。

Some examples are shown below. They should work on Linux or Mac.

下面显示了一些示例。他们应该在 Linux 或 Mac 上工作。

For Windows use _system and _popen instead, using if defined function of the C preprocessor.

对于 Windows,使用 _system 和 _popen 代替,使用 C 预处理器的 if 定义函数。

IFDEF Example

IFDEF 示例

#ifdef __unix__ /* __unix__ is usually defined by compilers targeting Unix systems */
# callto system goes here
#elif defined _WIN32 /* _Win32 is usually defined by compilers targeting 32 or 64 bit Windows   systems */
# callto _system goes here
#endif

They are architecture dependent, though the location of the firefox binary may not be on various systems.

它们依赖于体系结构,尽管 Firefox 二进制文件的位置可能不在各种系统上。

system

系统

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
    system("/usr/share/application/firefox");
    printf("Command done!");
    return 0;
}

popen

弹出

#include <stdio.h>
int main(int argc, char **argv))
{
   FILE *fpipe;
   char *command="/usr/share/application/firefox";
   char line[256];

   if ( !(fpipe = (FILE*)popen(command,"r")) )
   {  // If fpipe is NULL
      perror("Problems with pipe");
      exit(1);
   }

   while ( fgets( line, sizeof line, fpipe))
   {
     printf("%s", line);
   }
   pclose(fpipe);
   return 0;
}