Linux进程的堆栈大小与pthread、fork和exec有什么关系 [英] How is stack size of Linux process related to pthread, fork and exec

查看:29
本文介绍了Linux进程的堆栈大小与pthread、fork和exec有什么关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a question about the stack size of a process on Linux. Is this stack size determined at linkage time and is coded in the ELF file?

我写了一个程序,通过

I wrote a program which prints its stack size by

pthread_attr_getstacksize(&attr, &stacksize);

如果我直接从 shell 运行这个程序,它会给出大约 10MB 的值.但是当我从属于多线程程序的线程中 exec 时,它给出的值约为 2MB.

And if I run this program directly from a shell, it gives a value of about 10MB. But when I exec it from a thread which belongs to a multi-thread program, it gives a value of about 2MB.

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

So I want to know what factors affect the stack size of a process which is fork and exec-ed from some parent process. And is it possible to set the stack size of a process in its parent at run time before fork and exec the child?

推荐答案

作为 pthread_create(3) 说:

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

"On Linux/x86-32, the default stack size for a new thread is 2 megabytes", Unless the RLIMIT_STACK resource limit (ulimit -s) is set: in that case, "it determines the default stack size of new threads".

您可以通过使用 getrlimit(2),如以下程序:

You can check this fact by retrieving the current value of RLIMIT_STACK with getrlimit(2), as in the following program:

#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
", (size_t) rlim.rlim_cur);
    printf("%zd
", stacksize);
    pthread_attr_destroy(&attr);

    return 0;
}

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

These are the results when trying to run it (compiled to a.out) from the command line:

$ ulimit -s
8192
$ ./a.out 
8388608
8388608
$ ulimit -s unlimited
$ ./a.out 
-1
2097152
$ ulimit -s 4096
$ ./a.out 
4194304
4194304

这篇关于Linux进程的堆栈大小与pthread、fork和exec有什么关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆