How do I read the results of a system() call in C++?

后端 未结 9 930
醉梦人生
醉梦人生 2020-12-17 06:44

I\'m using the following code to try to read the results of a df command in Linux using popen.

#include  // file an         


        
9条回答
  •  庸人自扰
    2020-12-17 07:31

    (A note on terminology: "system call" in Unix and Linux generally refers to calling a kernel function from user-space code. Referring to it as "the results of a system() call" or "the results of a system(3) call" would be clearer, but it would probably be better to just say "capturing the output of a process.")

    Anyway, you can read a process's output just like you can read any other file. Specifically:

    • You can start the process using pipe(), fork(), and exec(). This gives you a file descriptor, then you can use a loop to read() from the file descriptor into a buffer and close() the file descriptor once you're done. This is the lowest level option and gives you the most control.
    • You can start the process using popen(), as you're doing. This gives you a file stream. In a loop, you can read using from the stream into a temporary variable or buffer using fread(), fgets(), or fgetc(), as Zarawesome's answer demonstrates, then process that buffer or append it to a C++ string.
    • You can start the process using popen(), then use the nonstandard __gnu_cxx::stdio_filebuf to wrap that, then create an std::istream from the stdio_filebuf and treat it like any other C++ stream. This is the most C++-like approach. Here's part 1 and part 2 of an example of this approach.

提交回复
热议问题