3

How to access pre-defined constant value from python with ctypes?

I have tried get a value, for example SIGTERM (it is clear that value be 15 in my environment x64 linux.) with ctypes.
Following is code that I wrote, but it raise a ValueError (Undefined Symbol). Why this error caused?

Note that I using Ubuntu 19.10, x64, Python 3.7.5

code:

from ctypes import *
from ctypes.util import *
libc_path = find_library("c")
libc = CDLL(libc_path)
sigterm_value = c_int.in_dll(libc, "SIGTERM")

1 Answer 1

2

That is because SIGTERM ([man7]: SIGNAL(7)) is a macro (#define: [GNU.GCC]: Object-like Macros) rather than a constant.
As a consequence, it doesn't reside in libc (meaning that you can't get it via CTypes), but it's just an alias (if you will), that is being replaced by the preprocessor to its value everywhere in (C) source code before compiling.

According to the (official) source file ([SourceWare]: [glibc.git]/bits/signum-generic.h):

#define SIGTERM     15  /* Termination request.  */

In Ubtu 16 64bit (I know it's old, but it's the only Nix VM running at this point), it ends up being defined in /usr/include/bits/signum.h:

#define SIGTERM         15      /* Termination (ANSI).  */

You should use [Python 3.Docs]: signal - Set handlers for asynchronous events:

>>> import signal
>>> signal.SIGTERM
<Signals.SIGTERM: 15>
>>> signal.SIGTERM.value
15
Sign up to request clarification or add additional context in comments.

1 Comment

What about constants like SEM_FAILED that aren't defined in any python standard library (checked os, fcntl, threading, and multiprocessing)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.