2

I am trying to use jemalloc for memory profiling, due to some reason i don't have control of parent process, So instead of setting MALLOC_CONF env variable outside, i am trying to set the variable within the program, but seems its not working.

I have tried setting the MALLOC_CONF env outside and then launch the process.. it works.

Below is the snippet of sample program

void keep_mallocing(int count, size_t size, int **ptr) {
        int i =0;
        for(i=0; i<count; i++) {
                ptr[i] = malloc(size);
                memset(ptr[i], 0, size);
        }
}

void keep_freeing(int count, int **ptr) {
        int i = 0;
        for(i=0; i<count; i++) {
                free(ptr[i]);
        }
}

void handle_sigusr1(int sig)
{
//      malloc_stats_print(NULL, NULL, "g,l,b,h,m,a");

        char *path = 0;
        path = getenv( "MALLOC_CONF" );
        printf("path : %s\n", path);

        mallctl("prof.dump", NULL, NULL, NULL, 0);
        return;
}

int
main(int argc, char **argv) {

        signal(SIGUSR1, handle_sigusr1);
        setenv("MALLOC_CONF", "prof:true,prof_prefix:jeprof.out", 1);
        while(1)
        {
                int *ptr[10] = {0};
                // count, bytes, ptr
                keep_mallocing(10, 1000000, ptr);

                sleep (1);
                // count, ptr
                keep_freeing(7, ptr);
                sleep (5);
        }

    return 0;
}

I m using below command to compile the code (I have tried both static and dynamic linking)

gcc -ggdb3 use_jemalloc.c -std=gnu99 -o abc /usr/local/lib/libjemalloc.a -lpthread -ldl -lm

If i export the variable and then run things seems to be working

$ ls
abc  use_jemalloc.c

$ export MALLOC_CONF="prof:true,prof_prefix:jeprof.out"

$ ./abc &
[1] 23220

$ kill -10 `pidof abc`
path : prof:true,prof_prefix:jeprof.out

$ ls
abc  jeprof.out.23220.0.m0.heap  use_jemalloc.c

But if u nullify the variable and then it doesn't generate anything

$ rm jeprof.*

$ ls
abc  use_jemalloc.c

$ export MALLOC_CONF=
$ echo $MALLOC_CONF


$ ./abc &
[1] 23244

$ kill -10 `pidof abc`
path : prof:true,prof_prefix:jeprof.out

$ ls
abc  use_jemalloc.c
4

1 回答 1

4

如果jemalloc只检查启动时的值,则可以检查是否MALLOC_CONF未设置环境变量,如果未设置,则可以设置它并重新exec使用设置的环境变量重新启动进程:

#include <unistd.h>
#include <stdlib.h>

int main( int argc, char **argv )
{
    char *envval = getenv( "MALLOC_CONF" );
    if ( NULL == envval )
    {
        setenv( "MALLOC_CONF", "prof:true,prof_prefix:jeprof.out", 1 );
        execv( argv[ 0 ], argv );
    }

    ...
}

请注意,如果之前运行的代码执行main()诸如打开文件之类的操作并使它们保持打开状态,这可能会导致问题。那不太可能。

于 2019-09-11T12:04:24.527 回答