- 论坛徽章:
- 7
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
int main(int argc,char *argv[])
{
int c,errflg = 0;
char *shmfile;
int rw = 0;
int ShmId;
struct shmid_ds shm_buf = { 0 };
struct stat stat_buf = { 0 };
char *shmp;
int fd;
ssize_t siz,offset = 0;
while ((c = getopt(argc, argv, "r:w:")) != EOF)
{
switch (c)
{
case 'r':
shmfile = strdup(optarg);
if (shmfile == NULL)
{
(void)fprintf(stderr,"Out of memory\n");
exit(252);
}
break;
case 'w':
shmfile = strdup(optarg);
rw = 1;
if (shmfile == NULL)
{
(void)fprintf(stderr,"Out of memory\n");
exit(253);
}
break;
case '?':
errflg++;
break;
} /* end switch */
if (errflg)
{
printf("Usage:%s -[r|w] file ShmId\n",argv[0]);
exit(1);
}
} /* end while */
if ((optind + 1) != argc)
{
printf("Usage:%s -[r|w] file ShmId\n",argv[0]);
exit(1);
}
if (rw)
fd = open(shmfile,O_WRONLY|O_CREAT|O_TRUNC);
else
{
fd = open(shmfile,O_RDONLY);
}
if (fd < 0)
{
perror("open:");
exit(4);
}
if (!rw && fstat(fd,&stat_buf))
{
perror("fstat:");
exit(5);
}
ShmId = atoi(argv[optind]);
if (shmctl(ShmId,IPC_STAT,&shm_buf))
{
perror("shmctl:");
exit(2);
}
if (rw)
shmp = shmat(ShmId,NULL,0);
else
shmp = shmat(ShmId,NULL,SHM_RDONLY);
if (!shmp)
{
perror("shmat:");
exit(3);
}
if (rw)
{
while((siz = write(fd,shmp + offset,shm_buf.shm_segsz - offset)))
{
if (siz == -1 && errno != EINTR && errno != EAGAIN)
{
perror("write:");
exit(6);
}
else if (siz > 0)
{
offset += siz;
}
else if (offset == shm_buf.shm_segsz)
{
break;
}
}
}
else
{
if (shm_buf.shm_segsz != stat_buf.st_size)
{
printf("The file size is not equal to shm size.\n");
exit(8);
}
while((siz = read(fd,shmp + offset,shm_buf.shm_segsz - offset)))
{
if (siz == -1 && errno != EINTR && errno != EAGAIN)
{
perror("write:");
exit(6);
}
else if (siz > 0)
{
offset += siz;
}
else if (offset == shm_buf.shm_segsz)
{
break;
}
}
}
close(fd);
shmdt(shmp);
return(0);
} |
备份或恢复共享内存块的小代码,刚搞完的。
[ 本帖最后由 syncpk99 于 2009-11-10 15:17 编辑 ] |
|