How can I reduce the memory footprint of a minimal Linux process
Asked Answered
C

1

7

Consider the following C program, 'pause.c':

void main() { pause(); }

Compiling this on x64 Linux 3.0.0-16-generic using this command 'gcc -Os pause.c -o pause' produces an executable of size ~8KB. When I run this executable and examine its precise memory footprint using 'pmap -d PID', it shows me that the private memory allocated to the process is 192KB (it varies across different systems usually, between 128KB and 192KB).

Examining the process using valgrind and massif fails to detect any memory allocation events. I was sceptical that the 192KB figure was accurate but I found that starting 5 instances of the 'pause' process did consume approximately 1MB of system memory.

I'm at a loss to explain the origin of this memory, can anyone provide some insight on why this memory is being allocated and any potential actions which could reduce it?, cheers.

Cortisone answered 27/3, 2012 at 10:23 Comment(5)
Start by checking the ELF executable; you'll find a lot of things in there (data/code sections, debug, comments, etc). Also bear in mind your program is linked against at least libc; that's quite a lot of space right there.Ambi
Ok, the base size of the binary is 8KB, and the pmap utility takes the linking overhead into account, the 192KB figure is derived solely from the program itself, this jumps to 4032KB when the linking overhead is considered but this is shared memory and not a concernCortisone
try to get rid of libc: void _start() { while (1) { } } and compile with gcc -nostdlib pause.c. This will reduce the memory usage.Prelect
and then limit the stack size to 12 bytes (ulimit -s 12) before running the binaryPrelect
Ah, the ulimit command did the trick!, it's down to 12kb, clearly the footprint was primarily caused by default stack allocation, please flesh out an answer to this effect and I will acceptCortisone
P
11

Reducing the stack limit will lower the memory footprint:

ulimit -s 8
Prelect answered 27/3, 2012 at 11:28 Comment(3)
setrlimit will do the same thing programaticallyCortisone
Not exactly the same! setrlimit will set the limit for the current process, but the stack will be allocated already... so the parent process must call setrlimit (that's what ulimit does) and then spawn the new process with small preallocated stack. Correct me if I'm wrong.Prelect
Using dietlibc can significantly reduce the overhead from glibc, the only problem is that all related components must be linked against dietlibc (such as openssl) fefe.de/dietlibcCortisone

© 2022 - 2024 — McMap. All rights reserved.