53 lines
1.2 KiB
C
Executable File
53 lines
1.2 KiB
C
Executable File
#define _GNU_SOURCE
|
|
|
|
#include <stdio.h>
|
|
#include <stddef.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
#include <linux/memfd.h>
|
|
#include <sys/syscall.h>
|
|
#include <sys/mman.h>
|
|
#include <fcntl.h>
|
|
|
|
#include "network.h"
|
|
#include "swap.h"
|
|
|
|
|
|
|
|
int make_swap(rbt_msg *swap)
|
|
{
|
|
swap->state = NEWMSG;
|
|
sem_post(&swap->status);
|
|
}
|
|
|
|
int create_swap(const char *name)
|
|
{
|
|
int fd = memfd_create(name,0);
|
|
|
|
//申请共享内存
|
|
ftruncate(fd, sizeof(rbt_msg));
|
|
//调整关闭策略
|
|
int flags = fcntl(fd, F_GETFD);
|
|
flags &= ~FD_CLOEXEC;
|
|
fcntl(fd, F_SETFD, flags);
|
|
//调整大小
|
|
rbt_msg *init_msg = (rbt_msg*)mmap(NULL, sizeof(rbt_msg), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
|
|
char buf[NET_MAX_MESSAGE_BUF] = {'\0'};
|
|
//初始化
|
|
memcpy(init_msg->raw_message,buf,NET_MAX_MESSAGE_BUF);
|
|
memcpy(init_msg->nickname,buf,64);
|
|
sem_init(&init_msg->status,1,1);
|
|
init_msg->raw_message[0] = '\0';
|
|
init_msg->state = FREE;
|
|
init_msg->uid[0] = '\0';
|
|
munmap((void*)init_msg,sizeof(rbt_msg));
|
|
return fd;
|
|
}
|
|
|
|
int close_swap(int shmid,rbt_msg *swap)
|
|
{
|
|
swap->state = QUITPLG;//置退出态
|
|
sem_post(&swap->status);//发送信号量
|
|
close(shmid);//关闭共享内存
|
|
} |