写一个melloc的C程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <signal.h>
#include <unistd.h>

#define SIGTERM_MSG "SIGTERM received.\n"

void sig_term_handler(int signum, siginfo_t *info, void *ptr)
{
write(STDERR_FILENO, SIGTERM_MSG, sizeof(SIGTERM_MSG));
}

void catch_sigterm()
{
static struct sigaction _sigact;

memset(&_sigact, 0, sizeof(_sigact));
_sigact.sa_sigaction = sig_term_handler;
_sigact.sa_flags = SA_SIGINFO;

sigaction(SIGTERM, &_sigact, NULL);
}

int main(int argc, char *argv[])
{
if ( argc != 2 )
{
printf("ERROR ELEMENT COUNTS.");
return 1;
}

// printf ("%ld\n", atol(argv[1]));

int *p;
long n = atol(argv[1]) * 1024 * 1024;

// printf ("%ld\n", n);

printf("Allocate Memory Size: %ld MB.\n", atol(argv[1]));

// Allocate Memory.
p = (int *)malloc(n);

if (p != NULL)
printf("SUCCESS.");
else
printf("FAILED.");

memset(p, 0, n);

catch_sigterm();

free(p);

sleep(3000);

return 0;
}

写一个Dockerfile

1
2
3
4
5
6
7
8
9
FROM alpine
RUN apk add build-base
COPY mem.c .
RUN gcc -o mem mem.c
# or RUN gcc -static -o mem mem.c

FROM alpine
COPY --from=0 ./mem .
ENTRYPOINT [ "/mem" ]

进行一个很新的测试

Build Image.

1
2
3
dive build -t liarlee-malloc:latest .
OR
docker build -t liarlee-malloc:latest .

Docker RUN.

1
2
docker run --name malloc --rm -dt liarlee-malloc:latest 200
# docker run --name malloc --rm -dt liarlee-malloc:latest [MemorySize(MB)]

Kubernetes Deployment RUN.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: liarlee-malloc
spec:
selector:
matchLabels:
app: malloc
replicas: 1
template:
metadata:
labels:
app: malloc
spec:
containers:
- name: malloc
image: liarlee-malloc:latest
args: [ "200" ]