shmcreate程序
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h> /* For mode constants */
#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
int main(int argc, char** argv)
{
int c, fd, flags;
char *ptr;
off_t length;
flags = O_CREAT | O_RDWR;
while((c = getopt(argc, argv, "e")) != -1)
{
switch(c)
{
case 'e':
flags |= O_EXCL;
break;
}
}
if(optind != argc - 2)
{
printf("usage: shmcreate [-e] <name> <length>");
}
length = atoi(argv[optind + 1]);
fd = shm_open(argv[optind], flags ,FILE_MODE);
ftruncate(fd, length);
ptr = mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
exit(0);
}
shmunlink程序
#include <sys/mman.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
if(argc != 2)
{
printf("usage: shmunlink <name>");
}
shm_unlink(argv[1]);
exit(0);
}
shmwrite程序
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
int main(int argc, char** argv)
{
int i, fd;
struct stat stat;
unsigned char *ptr;
if(argc != 2)
{
printf("usage: shmwrite <name>");
}
fd = shm_open(argv[1], O_RDWR, FILE_MODE);
fstat(fd, &stat);
ptr = mmap(NULL, stat.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
for(i = 0; i < stat.st_size; i++)
{
*ptr++ = i % 256;
}
exit(0);
}
shmread程序
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
int main(int argc, char** argv)
{
int i, fd;
struct stat stat;
unsigned char c, *ptr;
if(argc != 2)
{
prinf("usage: sharead <name>");
}
fd = shm_open(argv[1], O_RDONLY, FILE_MODE);
fstat(fd, &stat);
ptr = mmap(NULL, stat.st_size, PROT_READ, MAP_SHARED, fd, 0);
close(fd);
for(i - 0; i < stat.st_size; i++)
{
if((c = *ptr++) != (i % 256))
{
printf("ptr[%d] = %d", i, c);
}
}
exit(0);
}