【shell】shell脚本设置ulimit -c unlimited但脚本结束后系统ulimit -c未生效

问题现象

  • 在程序启动脚本中设置了ulimit -c unlimited,但是查看系统环境ulimit -c却未生效,仍显示0

  • 脚本如下

    #! /bin/bash
    ulimit -c unlimited
    echo "password" | sudo -S sysctl -w kernel.core_pattern=/your_path/core.%e.%p.%t.%s
    
    ./test/main	# 执行程序
    

问题原因

  • shell脚本中执行该命令,shell中内置命令只会影响当前shell会话及其子进程

  • 也就是说

    • 如果在脚本内设置了ulimit -c unlimited并同时启动程序,程序出现coredump是能记录core文件的
    • 但是脚本结束后再单独启动程序,ulimit -c unlimited可能没生效,程序奔溃后也未能记录core文件

测试程序

  • main.cpp

    include <iostream>
    include <string>
    
    using namespace std;
    
    int main()
    {
          
          
    	std::string my_str = “abcdef”;
    	auto* str_ptr = &my_str;
    	str_ptr[1] = 'g';
    	return 0;
    }
    
  • 编译

    g++ -o main main.cc
    
  • start.sh

    #! /bin/bash
    ulimit -c unlimited
    echo "password" | sudo -S sysctl -w kernel.core_pattern=/your_path/core.%e.%p.%t.%s
    
    ./main
    
  • ./start.sh启动程序出现coredump后,因为在同一会话中会保存core文件

解决方法

  • 要永久修改core文件限制,需修改系统的配置文件 /etc/security/limits.conf

    #* soft core 0
    
    修改为
    
    #* soft core unlimited       # 为所有用户设置无限制大小的core dump文件
    
  • 请注意,core dump文件可能占用大量磁盘空间,需确保指定路径有足够的可用空间


created by shuaixio, 2024.04.04

猜你喜欢

转载自blog.csdn.net/baidu_35692628/article/details/137187206