首页 > 解决方案 > 如何修复 Python 中的“无法从共享对象映射段”错误?

问题描述

我正在制作一个 Python 程序,它在运行程序时会限制可用内存。
使用内存限制为 1、2、3、4 和 5 MB 进行测试时,如果内存限制为 3 或 4 MB,则会出现以下错误。

./Main: error while loading shared libraries: libc.so.6: failed to map segment from shared object
Command '['./Main']' returned non-zero exit status 127.

libc.so.6 文件位于此位置。

/usr/lib64/libc.so.6

这是我的代码。

import resource
import subprocess
import os

MEMORY_LIMIT = 3 * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (MEMORY_LIMIT, MEMORY_LIMIT))
soft, hard = resource.getrlimit(resource.RLIMIT_AS)
rlimit = ("pid {pid} soft {soft} hard {hard}"
        .format(pid=os.getpid(), soft=soft, hard=hard))
print(rlimit)
try:
    r=subprocess.run(['./Main'], check=True)
except Exception as e:
    print(e)

它是 Main.c 代码。

#include <stdio.h>
int main() {
    int a, b;
    scanf("%d %d", &a, &b);
    printf("%d\n", a+b);
    return 0;
}

我使用“gcc -o Main -O2 -Wall Main.c”命令编译它。

我的问题是:

  1. 内存限制为5MB时运行正常,但是限制为3或4MB时为什么会出现这个错误?
  2. 与 RLIMIT_AS 不同,为什么 RLIMIT_DATA 或 RLIMIT_STACK 工作良好而不管内存限制?

请回答我是什么问题。

标签: pythonpython-3.xsubprocessresources

解决方案


推荐阅读