LoginSignup
5
10

More than 5 years have passed since last update.

Python3 からシステムコールを呼ぶ

Posted at

システムコールの番号を調べる

$ ausyscall --dump
0   read
1   write
2   open
3   close
...

$ ausyscall msgget --exact
68

または

/usr/include/x86_64-linux-gnu/sys/syscall.h
/usr/include/x86_64-linux-gnu/bits/syscall.h
/usr/include/x86_64-linux-gnu/asm/unistd_64.h

あたりを見ても分かるようです。

ctypes モジュールを利用して呼び出し

import ctypes
import os

# 上で調べたシステムコールの番号
SYS_getpid = 39
SYS_msgsnd = 69
SYS_msgrcv = 70


dll = ctypes.CDLL(None)

# 引数なしの例、引数が必要な場合は dll.syscall の第2引数以降に
res = dll.syscall(SYS_getpid)
if res < 0:
    # エラーの捕捉
    print(os.strerror(ctypes.get_errno()))


# 引数に配列が必要な場合は ctypes.create_string_buffer で生成
ptr = ctypes.create_string_buffer('hello\n'.encode('ascii'))
res = dll.syscall(SYS_msgsnd, msgid, ptr, len('hello\n'), 0)
if res < 0:
    print(os.strerror(ctypes.get_errno()))


# 配列に書き込みが行われる場合も ctypes.create_string_buffer で
ptr = ctypes.create_string_buffer(1024)
res = dll.syscall(SYS_msgrcv, msgid, ptr, 1024, 0, 0)
if res < 0:
    print(os.strerror(ctypes.get_errno()))
print(ptr.value)   # 配列の中身を取得

これで Python でなんでもできますね :-)

5
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
10