linux获取命令的输出值

  • Post author:
  • Post category:linux


/*
 * @FilePath: /command.cpp
 * @Author: Wilson
 * @Descripttion: 
 * @Date: 2020-12-05 10:23:14
 * @LastEditors: Wilson
 * @LastEditTime: 2020-12-05 12:11:02
 */

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

bool readcommand(std::string cmd)
{
    const char *sysCommand = cmd.data();
    FILE *fp = popen(sysCommand, "r");
    if (!fp)
    {
        std::cout << "popen error" << std::endl;
        return false;
    }
    char line[300];

    while (fgets(line, sizeof(line) - 1, fp) != NULL)
    {
        std::cout << line << std::endl;
        break;
    }
    pclose(fp);
    return true;
}

int main()
{
    std::string cmd = "ps -aux | grep \"rosboard\"";

    for (size_t i = 0; i < 1000; i++)
    {
        readcommand(cmd);
        sleep(1);
    }

    return 0;
}



版权声明:本文为wei242425445原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。