~emersion/mrsh

ref: fb1a6e2ce995f61ca8e41e8ac3f591bc50922592 mrsh/shell/shm.c -rw-r--r-- 642 bytes
fb1a6e2cemersion readme: add link to overall project status 3 years ago
                                                                                
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
#define _POSIX_C_SOURCE 199309L
#include <errno.h>
#include <sys/mman.h>
#include <time.h>
#include <string.h>
#include <fcntl.h>

static void randname(char *buf) {
	struct timespec ts;
	clock_gettime(CLOCK_REALTIME, &ts);
	long r = ts.tv_nsec;
	for (int i = 0; i < 6; ++i) {
		buf[i] = 'A'+(r&15)+(r&16)*2;
		r >>= 5;
	}
}

int create_anonymous_file(void) {
	int retries = 100;
	do {
		char name[] = "/mrsh-XXXXXX";
		randname(name + strlen(name) - 6);

		--retries;
		int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
		if (fd >= 0) {
			shm_unlink(name);
			return fd;
		}
	} while (retries > 0 && errno == EEXIST);

	return -1;
}