1. 程式人生 > 其它 >netdata:獲取系統最多能夠建立多少執行緒數

netdata:獲取系統最多能夠建立多少執行緒數

技術標籤:# C++

shell

$ cat /proc/sys/kernel/pid_max    #檢視系統支援的最大執行緒數
131072

c程式碼

#include <stdio.h>
#include <fcntl.h>
#include <zconf.h>

#define likely(x)  __builtin_expect((x), 1)
#define unlikely(x)  __builtin_expect((x), 0)
static inline int read_single_number_file(const char *filename,
unsigned long long *result); static inline int read_file(const char *filename, char *buffer, size_t size); static inline unsigned long long str2ull(const char *s); pid_t pid_max = 32768; pid_t get_system_pid_max(void) { static char read = 0; if(read) return pid_max; read = 1; char filename[
FILENAME_MAX + 1]; snprintf(filename, FILENAME_MAX, "/proc/sys/kernel/pid_max"); unsigned long long max = 0; if(read_single_number_file(filename, &max) != 0) { printf("Cannot open file '%s'. Assuming system supports %d pids.", filename, pid_max); return
pid_max; } if(!max) { printf("Cannot parse file '%s'. Assuming system supports %d pids.", filename, pid_max); return pid_max; } pid_max = (pid_t) max; return pid_max; } int main() { get_system_pid_max(); printf("pid_max = %d", pid_max); return 0; } static inline int read_single_number_file(const char *filename, unsigned long long *result) { char buffer[30 + 1]; int ret = read_file(filename, buffer, 30); if(unlikely(ret)) { *result = 0; return ret; } buffer[30] = '\0'; *result = str2ull(buffer); return 0; } static inline int read_file(const char *filename, char *buffer, size_t size) { if(unlikely(!size)) return 3; int fd = open(filename, O_RDONLY, 0666); if(unlikely(fd == -1)) { buffer[0] = '\0'; return 1; } ssize_t r = read(fd, buffer, size); if(unlikely(r == -1)) { buffer[0] = '\0'; close(fd); return 2; } buffer[r] = '\0'; close(fd); return 0; } static inline unsigned long long str2ull(const char *s) { unsigned long long n = 0; char c; for(c = *s; c >= '0' && c <= '9' ; c = *(++s)) { n *= 10; n += c - '0'; } return n; }

在這裡插入圖片描述