0

The following Linux command returns a single integer representing the number of cores on the processor (physical, not virtual cores):

grep ^cpu\\scores /proc/cpuinfo | uniq |  awk '{print $4}'

What is the best way to call this command in C and assign the result to a variable?

RTC222
  • 2,025
  • 1
  • 20
  • 53
  • [popen](http://man7.org/linux/man-pages/man3/popen.3.html). – kaylum Jan 21 '20 at 21:53
  • 1
    Is your question "how to run an arbitrary shell command and get it's output" or "how to get the number of CPU cores" ? – Eugene Sh. Jan 21 '20 at 21:59
  • @kaylum - the second answer (with 57 votes) looks promising -- fp = popen(cmd, "r"). I will try it in C now. – RTC222 Jan 21 '20 at 22:00
  • @Eugene Sh. - the command returns the number of physical cores, so my question is your first question, how to run the arbitrary command and assign its output to a variable in C. – RTC222 Jan 21 '20 at 22:01
  • @kaylum - no, that's a file command. I will try with system. – RTC222 Jan 21 '20 at 22:09
  • If you want to find the number of physical cores, you don't need to use external processes... – Shawn Jan 21 '20 at 22:16
  • @Shawn - how do we do that in C? – RTC222 Jan 21 '20 at 22:20
  • 1
    `fopen()` and reading /proc/cpuinfo yourself is one way. (There's also `get_nprocs()` or the equivalent `sysconf()` call, but I'm pretty sure that includes virtual cores) – Shawn Jan 21 '20 at 22:27
  • @Shawn - the command I gave above returns the physical processor count. My question is now to issue that command in C and capture its result to a variable. – RTC222 Jan 21 '20 at 22:32
  • 1
    It's an xy problem. You want x. You think y is a good approach when it's not, and are focusing on that instead of your real question. Or to put it another way, you're trying to use a semi to deliver an envelope. Just read the file in C using the normal stdio routines and extract the number. No need to get a shell or external programs involved. – Shawn Jan 21 '20 at 22:35
  • Reading all of /proc/cpuinfo then parsing it seems like the semi approach -- can you clarify what you mean. The command I gave delivers the answer as a single integer. I just need to capture it to a variable in C. Otherwise, I'm not sure exactly what approach you recommend. – RTC222 Jan 21 '20 at 22:43
  • 1
    `popen` is the way to do it if you want to run an external command. Not sure what you mean by "that's a file command". You can't do it (as easily) with `system` as that does not give you access to the output directly. – kaylum Jan 21 '20 at 23:01
  • 1
    I would look at using `fopen` to open the file for reading, and then use `getline` to parse line-by-line `strncmp` against the string you expect at the start of the line) until you find the correct line and then read the numeric value with `strtoul`. – Christian Gibbons Jan 21 '20 at 23:35

0 Answers0