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.
This commit is contained in:
Martin Storsjö 2014-01-21 12:19:22 +02:00
parent ae73411f9a
commit af6feaa45c

View File

@ -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 @@ WELS_THREAD_ERROR_CODE WelsQueryLogicalProcessInfo (WelsLogicalProcessInfo* p
//#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 WelsMultipleEventsWaitAllBlocking (uint32_t nCount, WE
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