在Python中如何在启用seccomp后干净退出?

4 投票
1 回答
1076 浏览
提问于 2025-04-19 23:04

我在一个项目中通过python-prctl启用了seccomp功能。现在我有点搞不清楚怎么才能正常退出,结果总是被杀掉。

我看到一些例子使用ctypes或ffi来尝试引用libc库,但如果我用WIFEXITED来检查,它们似乎也有同样的问题。

下面是示例代码。结果总是显示“我们被杀死了”。

def main():
  pid = os.fork()
  if not pid:
    prctl.set_seccomp(True)
    os.write(0, 'Hi\n')

#    os._exit(0)
#    _exit(0)
#    sys._exit(0)
#    return
#    ?!@#(*!  What do?

  endpid, status = os.waitpid(pid, 0)
  print 'Child forked as %d and returned with %d' % (endpid, status)
  if not os.WIFEXITED(status):
    print 'Exitted abnormally'
    if os.WIFSIGNALED:
      if os.WTERMSIG(status) == signal.SIGKILL:
        print 'We were killed to death'
  else:
    print 'Returned with %d' % (os.WEXITSTATUS(status))

我想补充一下,因为我忘了libc的部分:

即使在上面定义了_exit(),使用这两种方式仍然导致被杀掉。

# FFI Method
ffi = cffi.FFI()
# Use _exit, which avoids atexit(), etc
ffi.cdef('void _exit(int);')
libc = ffi.dlopen(None)
_exit = libc._exit

.... 或者 ....

# ctypes method
libc = cdll.LoadLibrary('libc-2.18.so')
_exit = libc._exit

1 个回答

5

有人帮我找到了这个答案:

In glibc up to version 2.3, the _exit() wrapper function invoked the kernel system
call of the same name.  Since glibc 2.3, the wrapper function invokes
exit_group(2), in order to terminate all of the threads in a process.

因为_exit这个函数会调用exit_group,而exit_group不在seccomp过滤器里面……所以它被杀掉了。用strace工具查看python执行的过程,可以看到exit_group这个调用。

撰写回答