Linux环境编程-- ftok()函数

2014-11-24 10:55:58 ? 作者: ? 浏览: 0

在成功获取到key之后,就可以使用该key作为某种方法的进程间通信的key值,例如shmget共享内存的方式。


shmget的函数原型为


int shmget( key_t, size_t, flag);


在创建成功后,就返回共享内存的描述符。在shmget中使用到的key_t就是通过ftok的方式生成的


实例:


#include
#include
#include
#include
#include


#define SIZE 1024


extern int errno;


int main()
{
int shmid;
char *shmptr;


//创建共享内存
if((shmid = shmget(IPC_PRIVATE, SIZE, 0600)) < 0)
{
printf("shmget error:%s\n", strerror(errno));
return -1;
}


//将共享内存连接到 可用地址上


if((shmptr = (char*)shmat(shmid, 0, 0)) == (void*)-1)
{
printf("shmat error:%s\n", strerror(errno));
return -1;
}
memcpy(shmptr, "hello world", sizeof("hello world"));
printf("share memory from %lx to %lx, content:%s\n",(unsigned long)shmptr, (unsigned long)(shmptr + SIZE), shmptr);


//拆卸共享内存
if((shmctl(shmid, IPC_RMID, 0) < 0))
{
printf("shmctl error:%s\n", strerror(errno));
return -1;
}
}


多进程之间共享内存情况:


#include
#include
#include
#include
#include
#include
#include
#include


#define SIZE 1024


extern int errno;


int main()
{
int shmid;
char *shmptr;
key_t key;
pid_t pid;


if((pid = fork()) < 0)
{
printf("fork error:%s\n", strerror(errno));
return -1;
}
else if(pid == 0)
{
sleep(2);
if((key = ftok("/dev/null", 1)) < 0)
{
printf("ftok error:%s\n", strerror(errno));
return -1;
}
if((shmid = shmget(key, SIZE, 0600)) < 0)
{
printf("shmget error:%s\n", strerror(errno));
exit(-1);
}


if((shmptr = (char*)shmat(shmid, 0, 0)) == (void*)-1)
{
printf("shmat error:%s\n", strerror(errno));
exit(-1);
}
//memcpy(shmptr, "hello world", sizeof("hello world"));
printf("child:pid is %d,share memory from %lx to %lx, content:%s\n",getpid(), (unsigned long)shmptr, (unsigned long)(shmptr + SIZE
), shmptr);
printf("child process sleep 2 seconds\n");
sleep(2);
if((shmctl(shmid, IPC_RMID, 0) < 0))
{
printf("shmctl error:%s\n", strerror(errno));
exit(-1);
}
exit(0);
}
//parent
else
{
if((key = ftok("/dev/null", 1)) < 0)
{
printf("ftok error:%s\n", strerror(errno));
return -1;
}
if((shmid = shmget(key, SIZE, 0600|IPC_CREAT|IPC_EXCL)) < 0)


{
printf("shmget error:%s\n", strerror(errno));
exit(-1);
}


if((shmptr = (char*)shmat(shmid, 0, 0)) == (void*)-1)
{
printf("shmat error:%s\n", strerror(errno));
exit(-1);
}
memcpy(shmptr, "hello world", sizeof("hello world"));
printf("parent:pid is %d,share memory from %lx to %lx, content:%s\n",getpid(),(unsigned long)shmptr, (unsigned long)(shmptr + SIZE
), shmptr);
printf("parent process sleep 2 seconds\n");
sleep(2);
if((shmctl(shmid, IPC_RMID, 0) < 0))
{
printf("shmctl error:%s\n", strerror(errno));
exit(-1);
}
}


waitpid(pid,NULL,0);
exit(0);
}


输出为:



shmctl(shmid, IPC_RMID, 0)的作用是从系统中删除该恭喜存储段。因为每个共享存储段有一个连接计数(shmid_ds结构中的shm_nattch),所以除非使用该段的最后一个进程终止与该段脱接,否则不会实际上删除该存储段。


-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: