0

Before nothing: I searched similar problems but none of the solutions seemed to work for me. Also please, I'm noob in C so sorry for the stupid mistakes that I can do. Thanks.

I have a little problem with my C++ file. What I want, is set a variable from a system("command"). I don't know if I'm explaining myself well so I put my file as an example. This is my file:

#include <stdlib.h>
#include <iostream>

using namespace std;

int main()
{
    int kernel = system("uname -a");
    //Here It should print the value but instead of that prints a zero :/
    printf("%d \n", kernel);
    return 0;
}

I'm trying to define the variable "kernel" from the output of system("uname -a") command that should be something like:

$ uname -a
Linux 5.0.0-27-generic #28~18.04.1-Ubuntu SMP Thu Aug 22 03:00:32 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

However, when I try to execute the code the output is just:

0

I'm missing something or this cannot be done in C++? Sorry for the noob question.

Best regards.

2 Answers2

2

system returns the error code, not a command output. 0 means no error. What you are looking for is popen.

#include <stdio.h>

char uname[1024];

FILE* fp = popen("uname -a", "r");
if (!fp)
    /* Handle error */;

if (fgets(uname, sizeof(uname), fp) != 0)
    std::cout << uname << std::endl;

int status = pclose(fp);
if (status == -1) {
    /* Error reported by pclose() */
}

Similar question demonstrates reading output data without length limit: popen() writes output of command executed to cout

273K
  • 19,191
  • 8
  • 34
  • 47
1

You need to use other function because system only return the code returned by the execution of the program. For example boost::process, this is a simple example

#include <boost/process.hpp>

using namespace boost::process;

int main()
{
    ipstream pipe_stream;
    child c("gcc --version", std_out > pipe_stream);

    std::string line;

    while (pipe_stream && std::getline(pipe_stream, line) && !line.empty())
        std::cerr << line << std::endl;

    c.wait();
}

Example taken from https://www.boost.org/doc/libs/1_71_0/doc/html/process.html

Empty Space
  • 723
  • 5
  • 17
Mauricio Ruiz
  • 322
  • 2
  • 10