title: Getting physical CPU count in Linux. parsing /proc/cpuinfo
body: <p>I was thinking about getting physical CPUs in Linux using C. I know, I can simply do this:</p>
  
  <pre><code>if(!(cpus = popen("cat /proc/cpuinfo | grep "physical id" | sort | uniq | wc -l
  ", "r")))
  {
      // ...
  }
  </code></pre>
  
  <p>but that's not the point, it won't work when I don't have <code>grep</code> installed. I came up with another idea:</p>
  
  <ol>
  <li>simply parse <code>/proc/cpuinfo</code></li>
  <li><p>count number of physical ids:</p>
  
  <pre><code>if(sscanf(buff, "physical id     : %d", &amp;physicalID) == 1)
      i++;
  </code></pre></li>
  <li><p>save them into an array: </p>
  
  <pre><code>if(sscanf(buff, "physical id     : %d", &amp;physicalID) == 1)
  {
      ids[i] = physicalID;
      i ++;
  }
  </code></pre></li>
  <li><p>check if there are different numbers in the array, if so, count them = it will give me number of physical sockets (CPUs), right?</p></li>
  </ol>
  
  <p>And I did it but I'm not quite sure if it will be always true ... And how about couting cores, logical CPUs and checking if hyperthreading is enabled? How can I do this with <code>/proc/cpuinfo</code> ?</p>