1.shm_open简单的使用
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc, char **argv)
{
int fd = 0;
int flags = 0;
int ch = 0;
int length = 0;
flags = O_RDWR | O_CREAT;
char *ptr = NULL;
char *ptrRead = NULL;
struct stat status;
char c;
while ((ch = getopt(argc, argv, "e")) != -1)
{
printf("%d\n", ch);
switch (ch)
{
case 'e':
{
flags |= O_EXCL;
break;
}
default:
{
break;
}
}
}
if (optind != argc - 2)
{
printf("usage:shmcreate [-e] <name> <length>");
exit(0);
}
length = atoi(argv[optind + 1]);
fd = shm_open(argv[optind], flags, 0666);
ftruncate(fd, length);
fstat(fd, &status);
ptr = (char *)(mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
for (int i = 0; i < status.st_size; i++)
{
*ptr++ = i % 256;
}
ptrRead = (char *)(mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
close(fd);
for (int i = 0; i < status.st_size; i++)
{
if ((c = *ptrRead++) != i % 256)
{
printf("error[%d]=%d\n", c, i % 256);
}
}
shm_unlink(argv[optind]);
return 0;
}