c++ - 获取 C 中后台 shell 命令的 PID

标签 c++ linux shell

我想从 C 程序中执行 Linux 命令并获取其 PID 及其输出。

例如在下面的executeShellCommand()函数中,如何获取启动进程的PID?

命令测试.cpp

#include <unistd.h>
#include <cstdio>
#include <iostream>
#include <string>
#include <stdexcept>

// execute a shell command and return its output
std::string executeShellCommand(const char* cmd) 
{
    char buffer[128];
    std::string result = "";
    FILE* pipe = popen(cmd, "r");
    if (!pipe) throw std::runtime_error("popen() failed!";
    try {
        while (!std::feof(pipe)) {
            if (std::fgets(buffer, sizeof buffer, pipe))
                result += buffer;
        }
    } catch (...) {
        pclose(pipe);
        throw;
    }
    pclose(pipe);
    return result;
}

int main(int argc, char* argv[])
{
    std::cout << "executeShellCommand : "
              << executeShellCommand(argv[1]) << std::endl;
    return 0;
}

测试.sh

#!/bin/bash
while [[ 1 ]]
do
   sleep 1
done

运行:

./commandTest "./test.sh & echo $!" 

最佳答案

你可以试试这个:

#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<fstream>
#include<string.h>
#include<ctime>
#include<iostream>
#include<string>
#include<cstdlib>
#include<sys/time.h>
#include<signal.h>
#include <stdexcept>
#include <functional> //for std::hash
#include <ctime>

using namespace std;

// execute a shell command and return its output
string executeShellCommand(const char* cmd) 
{
    char buffer[128];
    string result = "";
    FILE* pipe = popen(cmd, "r");
    if (!pipe) throw runtime_error("popen() failed!");
    try {
        while (!feof(pipe)) {
            if (fgets(buffer, 128, pipe) != NULL)
                result += buffer;
        }
    } catch (...) {
        pclose(pipe);
        throw;
    }
    pclose(pipe);

// remove new line character from result string
int pos;
while((pos=result.find('\n')) != string::npos)
                    result.erase(pos);
    return result;
}

int executeShellCommandPid(const char* cmd) 
{
string localCommand(cmd);

// make a file name using the input command and the current time
time_t rawtime;
struct tm * timeinfo;
char buffer[80];    
time (&rawtime);
timeinfo = localtime(&rawtime); 
strftime(buffer,sizeof(buffer),"%d-%m-%Y %I:%M:%S",timeinfo);
string currentTime(buffer); 
hash<string> hasher;
    string fileName = to_string(hasher(localCommand+currentTime)); 

localCommand = localCommand + " & echo $! | grep -w -o -E '[0-9]*'>" + fileName + ".pid";
system(localCommand.c_str());
localCommand = "cat " + fileName + ".pid";
int pid = stoi(executeShellCommand(localCommand.c_str()));
localCommand = "rm -rf " + fileName + ".pid";
system(localCommand.c_str());
return pid;
}

int main(int argc, char* argv[])
{
// variable definitions
string ARG_COM = argv[1];

cout << "system : " << system(ARG_COM.c_str()) << endl;
//cout << "executeShellCommand : " << executeShellCommand(ARG_COM.c_str()) << endl;
//cout << "executeShellCommandPid : " << executeShellCommandPid(ARG_COM.c_str()) << endl;

return 0;

}

关于c++ - 获取 C 中后台 shell 命令的 PID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45918306/

相关文章:

c++ - 对内部链接的困惑

linux - 在 ArchLinux 上使用 Plymouth

linux - linux shell 脚本中的一行 if/else 条件

sql-server - cakephp 2.0.5 Sqlserver 需要数据库连接

c++ - 有类似portablepython的C/C++项目吗?

c++ - 适用于 C 或 C++ 的 Google Drive API

Shell 脚本 - 使用 bin/echo 而不是 echo 的原因?

linux - BASH:将大小与另一个文件大小的百分比部分进行比较

linux - 使用 Sed 提取多个文件中的标题

c++ - “对象”尚未声明错误