linux上的进程堆栈大小如何与pthread,fork和exec相关

Fen*_*eng 15 size stack fork pthreads exec

我有一个关于Linux上进程的堆栈大小的问题.此堆栈大小是否在链接时确定并在ELF文件中编码?

我写了一个程序,打印出它的堆栈大小pthread_attr_getstacksize(&attr, &stacksize);.如果我直接从shell运行这个程序,它会提供大约10MB的值.但是当我exec从一个属于多线程程序的线程中,它给出了大约2MB的值.

所以我想知道哪些因素会影响fork and exec某个父进程的进程堆栈大小.是否可以fork and exec在孩子之前的运行时在其父级中设置进程的堆栈大小?
提前致谢.

Dan*_*nga 20

正如pthread_create(3)的联机帮助页所示:

" 在Linux/x86-32上,新线程的默认堆栈大小为2兆字节 ",除非设置了RLIMIT_STACK资源限制(ulimit -s):在这种情况下," 它确定新线程的默认堆栈大小 ".

您可以通过使用getrlimit(2)检索RLIMIT_STACK的当前值来检查此事实,如以下程序中所示:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>

int main()
{
    /* Warning: error checking removed to keep the example small */
    pthread_attr_t attr;
    size_t stacksize;
    struct rlimit rlim;

    pthread_attr_init(&attr);
    pthread_attr_getstacksize(&attr, &stacksize);
    getrlimit(RLIMIT_STACK, &rlim);
    /* Don't know the exact type of rlim_t, but surely it will
       fit into a size_t variable. */
    printf("%zd\n", (size_t) rlim.rlim_cur);
    printf("%zd\n", stacksize);
    pthread_attr_destroy(&attr);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这些是尝试从命令行运行(编译为a.out)时的结果:

$ ulimit -s
8192
$ ./a.out 
8388608
8388608
$ ulimit -s unlimited
$ ./a.out 
-1
2097152
$ ulimit -s 4096
$ ./a.out 
4194304
4194304
Run Code Online (Sandbox Code Playgroud)

  • 除此之外,linux会在需要时自动增加堆栈 - 但是您可能会受到这些限制,以及可扩展区域中可用地址空间的限制. (3认同)