Linux进程的堆栈大小与pthread,fork和exec如何相关 [英] How is stack size of Linux process related to pthread, fork and exec

查看:148
本文介绍了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?

我写了一个程序

pthread_attr_getstacksize(&attr, &stacksize);

如果我直接从外壳运行该程序,则它的值约为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 and exec -ed的进程的堆栈大小.并可以在运行时在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?

推荐答案

作为"在Linux/x86-32上,新线程的默认堆栈大小为2 MB ",除非设置了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\n", (size_t) rlim.rlim_cur);
    printf("%zd\n", 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天全站免登陆