蟒蛇ctypes的和的sysctl [英] python ctypes and sysctl

查看:140
本文介绍了蟒蛇ctypes的和的sysctl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code

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

libc = cdll.LoadLibrary(find_library("c"))
CTL_KERN = 1
KERN_SHMMAX = 34
sysctl_names = {
    'memory_shared_buffers' : (CTL_KERN, KERN_SHMMAX),
    }

def posix_sysctl_long(name):
    _mem = c_uint64(0)
    _arr = c_int * 2
    _name = _arr()
    _name[0] = c_int(sysctl_names[name][0])
    _name[1] = c_int(sysctl_names[name][1])
    result = libc.sysctl(_name, byref(_mem), c_size_t(sizeof(_mem)), None, c_size_t(0))
    if result != 0:
        raise Exception('sysctl returned with error %s' % result)
    return _mem.value

print posix_sysctl_long('memory_shared_buffers')

产生以下结果:

Traceback (most recent call last):
  File "test.py", line 23, in <module>
    print posix_sysctl_long('memory_shared_buffers')
  File "test.py", line 20, in posix_sysctl_long
    raise Exception('sysctl returned with error %s' % result)
Exception: sysctl returned with error -1

我客串我做错了什么。什么是正确的调用约定?我将如何找出究竟哪里出了问题?

I gues I did something wrong. What would be the correct calling convention? How would I find out what exactly went wrong?

推荐答案

您没有提供正确的值的sysctl功能。上)的sysctl(的参数的详细信息可以在这里找到

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

下面是你的错误:


  • 您已经忘记了的 nlen 的参数(第二个参数)

  • oldlenp 的参数是一个指针的大小,没有直接的大小

  • 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

这篇关于蟒蛇ctypes的和的sysctl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆