shm implemented as memfd syscall
zhangmeng
2023-07-27 157b3411dd123694ca29dd80fe9ecc683958ccab
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
61
62
63
64
65
66
#include <cstring>
#include <stdio.h>
#include <unistd.h>
 
#include <sys/types.h>
#include <sys/stat.h>
 
#include "src2/shmh.h"
 
#include <chrono>
 
int main(int argc, char const *argv[])
{
    int sock = unix_domain_client_fd("/tmp/memfd_shm.sock", 0);
    if (sock <= 0){
        printf("unix_domain_client_fd failed\n");
        return -1;
    }
 
    int count = 0;
 
    using namespace std::chrono;
    auto s = steady_clock::now();
    auto e = s;
 
    while (true) {
 
        int recvfds[16];
        memset(recvfds, 0, sizeof(int)*16);
        int fd = recvfd(sock, recvfds, 16);
        if (fd < 0){
            printf("memfd %d no exist\n", fd);
            continue;
        }
        // struct stat st;
        // if (fstat (fd, &st))
        // {
        //     return -1;
        // }
        // printf("st size %ld\n", st.st_size);
 
        count++;
 
        unsigned char* addr;
        int len = basic_shm_mmap(recvfds[0], &addr);
        if (len <= 0) break;
        printf("======>> mmap len %d msg %s\n", len, addr);
        basic_shm_unmmap(fd, &addr);
        for (int i = 0; i < 16; i++) {
            close(recvfds[i]);
        }
        usleep(20000);
 
        // e = steady_clock::now();
        // if (duration_cast<milliseconds>(e-s).count() > 1000){
        //     s = e;
        //     printf("======>> around 1 s recv count %d\n", count);
        //     _exit(0);
        //     count = 0;
        // }
    }
 
    close(sock);
 
    return 0;
}