C++ 在linux環境獲取命令行返回值


很多時候我們需要 上層代碼需要執行 shell 命令,但還要有返回值,例如需要獲取 ls 的返回值

接下來介紹幾種編程語言的獲取命令的返回值的方法

第一種 C++

代碼如下:

#include <iostream>
#include <string>
#include <stdio.h>
 
int exec_cmd(std::string cmd, std::string &res){
  if (cmd.size() == 0){  //cmd is empty 
    return -1;
  }
 
  char buffer[1024] = {0};
  std::string result = "";
  FILE *pin = popen(cmd.c_str(), "r");
  if (!pin) { //popen failed 
    return -1;
  }
 
  res.clear();
  while(!feof(pin)){
    if(fgets(buffer, sizeof(buffer), pin) != NULL){
      result += buffer;
    }
  }
 
  res = result;
  return pclose(pin); //-1:pclose failed; else shell ret
}
 
int main(){
  std::string cmd = "ls -ial";
  std::string res;
 
  std::cout << "ret = " << exec_cmd(cmd, res) << std::endl;
  std::cout << res << std::endl;
 
  return 0;
}

運行結果:

ret = 0
總用量 164
  17 drwxrwx--- 1 root vboxsf  4096 12月 25 17:09 .
   1 drwxrwx--- 1 root vboxsf  8192 12月 18 17:11 ..
9325 -rwxrwx--- 1 root vboxsf 14652 12月 25 16:56 a.out
  55 drwxrwx--- 1 root vboxsf  4096 11月  5 16:20 c++
  57 drwxrwx--- 1 root vboxsf  4096 11月  5 15:17 DesignPatterns-master
7701 -rwxrwx--- 1 root vboxsf 94688 11月  5 09:01 DesignPatterns-master.zip
  79 drwxrwx--- 1 root vboxsf  4096 8月  26 08:59 gototext
9328 -rwxrwx--- 1 root vboxsf 14652 12月 25 17:09 main
9324 -rwxrwx--- 1 root vboxsf   722 12月 25 17:07 mianText.cpp
  82 drwxrwx--- 1 root vboxsf  4096 11月  5 16:02 text1
  54 drwxrwx--- 1 root vboxsf  4096 11月  5 15:17 .vscode

第二種 QT 開啟進程的方法

代碼如下:

    // 調用  QProcess 頭文件    開個進程綁定信號 在槽函數提取自己想要的數據
userNameProcess = new QProcess; userNameProcess->start("who"); connect(userNameProcess,SIGNAL(readyReadStandardOutput()) ,this, SLOT(getUserNameProcessSlot())); void MainWindow::getUserNameProcessSlot() { QString temp = userNameProcess->readAll(); Singleton::mutexWiFi.lock(); Singleton::userNameGlobal = temp.mid(0,temp.indexOf(" ",0)); Singleton::mutexWiFi.unlock(); qDebug() << "用戶名:" <<Singleton::userNameGlobal<< endl; }

第三種 python

代碼如下:

import commands
 
status, output = commands.getstatusoutput('ls -lt')
 
print status
print output

 


免責聲明!

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



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