C++ read and log linux command in physical file

#include <iostream>
#include <chrono>
#include <thread>
#include <functional>
#include <uuid/uuid.h>
#include <cstdlib>
#include <fstream>

using namespace std;

static char *dtValue=(char*)malloc(20);
static char *uuidValue = (char *)malloc(40);

char *getTimeNow()
{
    time_t rawTime = time(NULL);
    struct tm tmInfo = *localtime(&rawTime);
    strftime(dtValue, 20, "%Y%m%d%H%M%S", &tmInfo);
    return dtValue;
}


void executeLinxCommand();

int main()
{
    executeLinxCommand();
}

void executeLinxCommand()
{
    string cmdText="ps -ef|grep h1 >test.txt";
    system(cmdText.c_str());
    fstream rFile("test.txt",ios::in);
    if(!rFile.is_open())
    {
        cout<<"Open test.txt failed!"<<endl;
        return;
    }

    string line;
    string key="./h1";
    while(getline(rFile,line))
    {
        if(line.find(key)!=std::string::npos)
        {
            cout<<"Key="<<key<<endl;
            break;
        }
    }

    cout<<"Finsihed in executeLinxCommand() and now is "<<getTimeNow()<<endl;
    free(dtValue);
    free(uuidValue);
}

Compile

g++ -g h2.cpp -o h2 -lpthread -luuid

Run ./h2

 

posted @ 2021-12-28 19:06  FredGrit  阅读(27)  评论(0编辑  收藏  举报