C++ 執行 Linux shell 命令並獲取命令返回值或命令執行結果


這里只做展示作用,可能更新不及時,獲取源碼請移步gitee個人倉庫:shell

1. 環境

  • Linux(Ubuntu)
  • C++11
  • gcc 7.5.0
  • g++ 7.5.0

2. 代碼

Shell.h

/*
*Environment:
*Linux(Ubuntu), C++11,gcc 7.5.0,g++ 7.5.0
*Description:
*執行 Linux shell 命令並獲取命令返回值或命令執行結果
*/

#ifndef PARAMETER_FLOW
#define PARAMETER_FLOW
#define IN
#define OUT
#define INOUT
#endif    //PARAMETER_FLOW

#ifndef BASE_TYPE_DEF
#define BASE_TYPE_DEF
#include <stdint.h>
typedef int16_t          SHORT;
typedef uint16_t         USHORT;
typedef int32_t          INT;
typedef uint32_t         UINT;
typedef int64_t          DLONG;
typedef uint64_t         DULONG;
typedef void             VOID;
typedef bool             BOOL;
typedef char             CHAR;
typedef unsigned char    UCHAR;
typedef float            FLOAT;
typedef double           DOUBLE;
#endif    //BASE_TYPE_DEF

#include <string>
#include <string.h>
#include <utility>
#include <vector>

using std::make_pair;
using std::pair;
using std::string;
using std::vector;

class Shell
{
public:

    /*
    *Function    : exeShellCmd
    *Description : 執行 Linux shell 命令並獲取命令返回值
    *Modify      : 2020.09.17
    *Input       : IN const string& cmd = "",Linux shell 命令
    *            : OUT INT* cmdReturnValue = nullptr,命令返回值
    *Return      : pair<BOOL, string>,<函數是否執行成功,執行失敗時的錯誤信息>
    *Caution     :
    */
    static pair<BOOL, string> exeShellCmd(IN const string& cmd = "", OUT INT* cmdReturnValue = nullptr);

    /*
    *Function    : exeShellCmd
    *Description : 執行 Linux shell 命令並獲取命令執行結果
    *Modify      : 2020.09.17
    *Input       : IN const string& cmd,Linux shell 命令
    *            : OUT vector<string>& results,命令執行結果
    *Return      : pair<BOOL, string>,<函數是否執行成功,執行失敗時的錯誤信息>
    *Caution     :
    */
    static pair<BOOL, string> exeShellCmd(IN const string& cmd, OUT vector<string>& results);

};    //Shell

 

Shell.cpp

 

#include "Shell.h"

pair<BOOL, string> Shell::exeShellCmd(IN const string &cmd, OUT INT *cmdReturnValue)
{
    pid_t status;                 //pid_t 就是 int
    status = system(cmd.c_str()); //階段1:創建子進程等准備工作,如果失敗返回 -1
    if (-1 == status)
    {
        return make_pair(false, "階段1:創建子進程等准備工作錯誤, 錯誤信息:" + string(strerror(errno)));
    }
    else
    {
        //階段2:調用 /bin/sh 拉起腳本執行,如果腳本拉起失敗或腳本未正常執行結束,則原因值被寫入到 status 的低 8~15 比特位中。
        //不管腳本中返回什么值,是 0 還是非 0,都算正常執行結束。即使腳本不存在或沒有執行權限,也都算正常執行結束。
        //如果腳本執行過程中被強制 kill 掉等情況則算異常結束。
        if (WIFEXITED(status))
        {
            if (nullptr != cmdReturnValue)
            {
                *cmdReturnValue = WEXITSTATUS(status); //獲取腳本返回值,一般腳本或命令正確執行返回值是 0,執行錯誤返回其它值
            }
            return make_pair(true, "");
        }
        else
        {
            return make_pair(false, "階段2:調用 /bin/sh 拉起腳本(命令)執行,腳本(命令)拉起失敗或腳本(命令)未正常執行結束");
        }
    }
} //exeShellCmd()

pair<BOOL, string> Shell::exeShellCmd(IN const string &cmd, OUT vector<string> &results)
{
    INT bufferSize = 10240; //10KB應該是非常充足了
    CHAR *buffer = new CHAR[bufferSize];
    FILE *pFile = NULL;
    if (NULL == (pFile = popen(cmd.c_str(), "r")))
    {
        return make_pair(false, "execute shell command error");
    }
    while (NULL != fgets(buffer, bufferSize, pFile))
    {
        buffer[strlen(buffer) - 1] = '\0'; //fgets() 會自動在末尾加入換行符,linux 下換行符就是 \n(LF),這里把自動添加的換行符去掉
        results.emplace_back(buffer);
    }
    delete[] buffer;
    pclose(pFile);
    return make_pair(true, "");
} //exeShellCmd()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM