进程空间分配和堆栈大小
1. Linux中进程空间的分配情况如下:
从上图可以看出,进程的空间分配:与进程相关的数据结构(页表、内核栈、task) ---> 物理内存 ---> 内核代码和数据 ---> 用户栈 ---> 共享库的内存映射区 ---> 运行时堆 --->未初始化数据段.bss ---> 已初始化数据段.data ---> 代码段.text
2. 进程的堆栈大小:
- 32位Windows,一个进程栈的默认大小是1M,在vs的编译属性可以修改程序运行时进程的栈大小。
- Linux下进程栈的默认大小是10M,可以通过 ulimit -s查看并修改默认栈大小。
- 默认一个线程要预留1M左右的栈大小,所以进程中有N个线程时,Windows下大概有N*M的栈大小。
- 堆的大小理论上大概等于进程虚拟空间大小-内核虚拟内存大小。windows下,进程的高位2G留给内核,低位2G留给用户,所以进程堆的大小小于2G。Linux下,进程的高位1G留给内核,低位3G留给用户,所以进程堆大小小于3G。
3. 进程的最大线程数:
- 32位windows下,一个进程空间4G,内核占2G,留给用户只有2G,一个线程默认栈是1M,所以一个进程最大开2048个线程。当然内存不会完全拿来做线程的栈,所以最大线程数实际值要小于2048,大概2000个。
- 32位Linux下,一个进程空间4G,内核占1G,用户留3G,一个线程默认8M,所以最多380个左右线程。(ps:ulimit -a 查看电脑的最大进程数,大概7000多个)
- https://www.cnblogs.com/ladawn/p/8449399.html
-
linux查看修改线程默认栈空间大小(ulimit -s)
1.linux查看修改线程默认栈空间大小 ulimit -s
a、通过命令 ulimit -s 查看linux的默认栈空间大小,默认情况下 为10240 即10M
b、通过命令 ulimit -s 设置大小值 临时改变栈空间大小:ulimit -s 102400, 即修改为100M
c、可以在/etc/rc.local 内 加入 ulimit -s 102400 则可以开机就设置栈空间大小
d、在/etc/security/limits.conf 中也可以改变栈空间大小:
#<domain> <type> <item> <value>
* soft stack 102400
重新登录,执行ulimit -s 即可看到改为102400 即100M
2.为啥linux要限制用户进程的栈内存大小。
Why does Linux have a default stack size soft limit of 8 MB?
The point is to protect the OS.
Programs that have a legitimate reason to need more stack are rare. On the other hand, programmer mistakes are common, and sometimes said mistakes lead to code that gets stuck in an infinite loop. And if that infinite loop happens to contain a recursive function call, the stack would quickly eat all the available memory. The soft limit on the stack size prevents this: the program will crash but the rest of the OS will be unaffected.
Note that as this is only a soft limit, you can actually modify it from within your program (see setrlimit(2): get/set resource limits) if you really need to.