summaryrefslogtreecommitdiffstats
path: root/how-to-update-process.c
blob: 6328ecf6647d7096699c600ee69a915a205827c7 (plain) (blame)
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
#include <sys/auxv.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>


static const char *text = "Change this text and recompile while the process is running";


int
main(int argc, char *argv[])
{
	uintptr_t exe_addr = (uintptr_t)getauxval(AT_EXECFN);
	const char *exe;

	if (!exe_addr) {
		fprintf(stderr, "%s\n", "Sorry, AT_EXECFN not found, would have to use /proc/self/exe, which is out of scope");
		/* by the way, if you just exec into /proc/self/exe
		 * you restart the process, to the same version as
		 * running even if it has been replaced (define
		 * RESTART to try it out) */
		return 1;
	}
	exe = (void *)exe_addr; /* beware, this might be a relative path */

	if (argc != 2 || strcmp(argv[1], text))
		printf("%s\n", text);

	unlink(exe);

	for (;;) {
		sleep(1);
#ifdef RESTART
		execlp("/proc/self/exe", argv[0], text, NULL);
		abort();
#else
		execlp(exe, argv[0], text, NULL);
#endif
	}
}