shithub: openh264

Download patch

ref: af6feaa45c4a865f91eb8c1b049e51dffa2e7456
parent: ae73411f9ab5de7f104d8bc046fc9db8ec05f716
author: Martin Storsjö <[email protected]>
date: Tue Jan 21 07:19:22 EST 2014

Use sched_getaffinity to get the number of cores on linux

This gets rid of the code that parses /proc/cpuinfo, and avoids
forking within the library.

The previous code also failed build on modern glibc versions
due to ignoring the return value of the system, read and write
system calls.

--- a/codec/common/WelsThreadLib.cpp
+++ b/codec/common/WelsThreadLib.cpp
@@ -39,6 +39,13 @@
  */
 
 
+#ifdef LINUX
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include <sched.h>
+#endif
+
 #include "WelsThreadLib.h"
 #include <stdio.h>
 
@@ -180,47 +187,6 @@
 //#include <Gestalt.h>
 #endif//MACOS
 
-static int32_t  SystemCall (const str_t* pCmd, str_t* pRes, int32_t iSize) {
-  int32_t fd[2];
-  int32_t iPid;
-  int32_t iCount;
-  int32_t left;
-  str_t* p = NULL;
-  int32_t iMaxLen = iSize - 1;
-  memset (pRes, 0, iSize);
-
-  if (pipe (fd)) {
-    return -1;
-  }
-
-  if ((iPid = fork()) == 0) {
-    int32_t  fd2[2];
-    if (pipe (fd2)) {
-      return -1;
-    }
-    close (STDOUT_FILENO);
-    dup2 (fd2[1], STDOUT_FILENO);
-    close (fd[0]);
-    close (fd2[1]);
-    system (pCmd);
-    read (fd2[0], pRes, iMaxLen);
-    write (fd[1], pRes, strlen (pRes));	// confirmed_safe_unsafe_usage
-    close (fd2[0]);
-    close (fd[1]);
-    exit (0);
-  }
-  close (fd[1]);
-  p = pRes;
-  left = iMaxLen;
-  while ((iCount = read (fd[0], p, left))) {
-    p += iCount;
-    left -= iCount;
-    if (left <= 0) break;
-  }
-  close (fd[0]);
-  return 0;
-}
-
 void WelsSleep (uint32_t dwMilliseconds) {
   usleep (dwMilliseconds * 1000);	// microseconds
 }
@@ -483,19 +449,16 @@
 WELS_THREAD_ERROR_CODE    WelsQueryLogicalProcessInfo (WelsLogicalProcessInfo* pInfo) {
 #ifdef LINUX
 
-#define   CMD_RES_SIZE    2048
-  str_t pBuf[CMD_RES_SIZE];
+  cpu_set_t cpuset;
 
-  SystemCall ("cat /proc/cpuinfo | grep \"processor\" | wc -l", pBuf, CMD_RES_SIZE);
+  CPU_ZERO (&cpuset);
 
-  pInfo->ProcessorCount = atoi (pBuf);
-
-  if (pInfo->ProcessorCount == 0) {
+  if (!sched_getaffinity (0, sizeof (cpuset), &cpuset))
+    pInfo->ProcessorCount = CPU_COUNT (&cpuset);
+  else
     pInfo->ProcessorCount = 1;
-  }
 
   return WELS_THREAD_ERROR_OK;
-#undef   CMD_RES_SIZE
 
 #else