dporu02280 2018-01-17 06:43
浏览 159

使用rlimit限制子进程的内存使用量,而不影响当前进程

I want to limit the memory usage of a child process using rlimit. Currently our code is as follows:

old_rlimit := get_rlimit()
set_rlimit(child_process_rlimit)
cmd.Start()
set_rlimit(old_rlimit)
cmd.Wait()

However, sometimes Golang runtime will report out of memory error at cmd.Start(). It seems that in cmd.Start() current process will allocate some memory, and if current memory usage is higher than child_process_rlimit, an error will be raised.

I want to know is there any way to limit the memory usage of child process without affecting current one?

  • 写回答

1条回答 默认 最新

  • dpw50696 2018-01-17 07:34
    关注

    You need to apply rlimit to the child process only rather than relying on rlimit inheritance. Your main blocker here is clearly spelled out in the setrlimit man page:

    an unprivileged process may set only its soft limit to a value in the range from 0 up to the hard limit, and (irreversibly) lower its hard limit

    The standard way to do this is through fork/exec, something along the lines of:

    child_pid := fork()
    if pid != 0 {
      // in child process
      setrlimit(...)
      execve(...)
    }
    

    If you don't want to do that, you still have a few options:

    • run as privileged user
    • cmd.Run a small wrapper (eg: bash ulimit -m ...) that calls the child process. note: -m is not honored by many systems.
    • call prlimit (linux-specific and no syscall wrapper. see this thread for details)
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮