#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#define SHM_NAME "aaa.txt"
int mmap_write()
{
int fd;
char *shm;
int data;
if ((fd = open(SHM_NAME, O_CREAT | O_RDWR, 0644)) < 0) {
return 0;
}
truncate(SHM_NAME, sysconf(_SC_PAGE_SIZE));
shm = mmap(0, sysconf(_SC_PAGE_SIZE), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
if (shm == MAP_FAILED) {
return 0;
}
data=119;
*(int*)shm = data;
return 1;
}
int mmap_read()
{
int fd;
char *shm;
int data;
if ((fd = open(SHM_NAME, O_CREAT | O_RDWR, 0644)) < 0) {
return 0;
}
truncate(SHM_NAME, sysconf(_SC_PAGE_SIZE));
shm = mmap(0, sysconf(_SC_PAGE_SIZE), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
if (shm == MAP_FAILED) {
return 0;
}
data = *(int*)shm;
printf("[mmap_read]data=%d\n", data);
return 1;
}
int shm_write()
{
void *shm = NULL;
int shmid;
int data;
shmid = shmget((key_t)1000, sizeof(int), 0666|IPC_CREAT);
if (shmid == -1) {
return 0;
}
shm = shmat(shmid, 0, 0);
if (shm == (void*)-1) {
return 0;
}
memset(&data, 0x00, sizeof(int));
data = 110;
*(int*)shm = data;
return 1;
}
int shm_read()
{
void *shm = NULL;
int shmid;
int data;
shmid = shmget((key_t)1000, sizeof(int), 0666|IPC_CREAT);
if (shmid == -1) {
return 0;
}
shm = shmat(shmid, 0, 0);
if (shm == (void*)-1) {
return 0;
}
data = *(int*)shm;
printf("[shm_read]data=%d\n", data);
return 1;
}
int main(int argc, char *argv[])
{
if(atoi(argv[1]) == 0) {
shm_write();
mmap_write();
} else {
shm_read();
mmap_read();
}
return 0;
}
linuxC 共享内存实例(shmget和mmap)
最新推荐文章于 2024-05-06 17:54:39 发布