0

I try to get output of nvidia-smi command from c using popen as here

C: Run a System Command and Get Output?

The command is stored in a buffer string and the same string is used to store the output:

    const size_t pid = getpid();

    char pid_s[1000];

    sprintf(pid_s, "%lu", pid);

    FILE *file_command = NULL;

    char buffer[1000];

    sprintf(buffer, "nvidia-smi | grep %s |awk '{print $6}'", pid_s);

    file_command = popen(buffer, "r");

    if (file_command == NULL) //No error : file_command is not NULL
    {
        throw std::runtime_error("Command failed to execute");
    }

    sleep(4); //To get time for the command to be executed.

    while (fgets(buffer, sizeof(buffer), file_command) != NULL) //Read output
    {
        printf("Result from command %s \n", buffer); //Nothing printed
    }

...

I try to get the 6th argument of nvidia-smi output which is the memory of the program currently running (Its pid is taken from getpid()).

Nothing is printed to screen.

fgets returns NULL although memory has been allocated on GPU (with cudaMalloc).

And I have been taking care of using sleep as recommended in this post

fgets returning error for FILE returned by popen

4Rom1
  • 81
  • 6
  • You do realise that this approach is fragile and may break at any time when NVidia changes the output format of `nvidia-smi` - right? – Jesper Juhl Mar 13 '20 at 17:25
  • Ok yes. It might not be the best approach indeed. I need a way to get the memory consumption of a process on GPU directly from c. The function cudaMemGetInfo gives the total and free memory which I am not interested in – 4Rom1 Mar 13 '20 at 17:52

1 Answers1

0

I finally found a better way to get GPU memory from c by using NVML

library as suggested in this post.

Usage from c is pretty straightforward (see here for example)

4Rom1
  • 81
  • 6