key_t ftok(const char *pathname, int proj_id);
pathname参数: 必须是一个已经存在且程序可范围的文件。
proj_id参数: 虽然定义为一个整数,其实实际只有8个bit位有效,即如果该参数大于255,则只有后8bit有效。
函数作用: convert a pathname and a project identifier to a System V IPC key, Key可用于msgget, semget, or shmget的key参数
示例:
#define SHMSIZE 256
key_t shmKey = ftok(“/tmp”, 128);
if (-1 == shmKey)
{
printf("ERROR: ftok faield, %s. ", strerror(errno));
exit(-1);
}
//创建共享内存
int shmid = shmget(shmKey, SHMSIZE, 0666);
if (-1 == shmid)
{
shmid = shmget(shmKey, SHMSIZE, IPC_CREAT | 0666);
if (-1 == shmid)
{
shmid = shmget(shmKey, 0, 0666);
if (shmid >= 0)
{
shmctl(shmid, IPC_RMID, NULL);
shmid = shmget(shmKey, SHMSIZE, IPC_CREAT | 0666);
}
if (-1 == shmid)
{
printf("ERROR: call shmget failed, %s. ", strerror(errno));
exit(-1);
}
}
//链接共享内存
char *shmptr = (char *)shmat(shmid, (char *) 0, 0666);
if (shmptr == (char *)(-1))
{
printf("Call shmat() failed, %s. ", strerror(errno));
exit(-1);
}
//拆卸共享内存
if ((shmctl(shmid, IPC_RMID, 0) < 0))
{
printf("shmctl error:%s ", strerror(errno));
return -1;
}
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.mushiming.com/mjsbk/5716.html