python ctypes and sysctl

后端 未结 1 1502
Happy的楠姐
Happy的楠姐 2020-12-18 13:11

I have following code

import sys
from ctypes import *
from ctypes.util import find_library

libc = cdll.LoadLibrary(find_library(\"c\"))
CTL_KERN = 1
KERN_SH         


        
1条回答
  •  死守一世寂寞
    2020-12-18 13:52

    You are not providing the correct values to the sysctl function. Detailed information on the arguments of sysctl() can be found here.

    Here are your errors:

    • You have forgotten the nlen argument (second argument)
    • The oldlenp argument is a pointer to the size, not directly the size

    Here is the correct function (with minor improvement):

    def posix_sysctl_long(name):
        _mem = c_uint64(0)
        _def = sysctl_names[name]
        _arr = c_int * len(_def)
        _name = _arr()
        for i, v in enumerate(_def):
            _name[i] = c_int(v)
        _sz = c_size_t(sizeof(_mem))
        result = libc.sysctl(_name, len(_def), byref(_mem), byref(_sz), None, c_size_t(0))
        if result != 0:
            raise Exception('sysctl returned with error %s' % result)
        return _mem.value
    

    0 讨论(0)
提交回复
热议问题