当前位置: 技术问答>linux和unix
共享内存
来源: 互联网 发布时间:2015-08-20
本文导语: 在solaris9上 #include #include #include #include #include #include int main() { int shm_id, shm_mat, i; key_t key; char temp; char* p_map; char* name = "/tmp/myshm2"; key = ftok(name, 0); printf("key=%dn", key); if(key == -1){ printf("ftok ...
在solaris9上
#include
#include
#include
#include
#include
#include
int main()
{
int shm_id, shm_mat, i;
key_t key;
char temp;
char* p_map;
char* name = "/tmp/myshm2";
key = ftok(name, 0);
printf("key=%dn", key);
if(key == -1){
printf("ftok error");
return -1;
}
shm_id = shmget(key,4096,IPC_CREAT);
printf("shmget=%dn", shm_id);
if(shm_id == -1)
{
printf("shmget error");
return -1;
}
p_map = (char*)shmat(shm_id,NULL,0);
printf("shmat %dn", p_map);
temp = 'a';
printf("before memcpyn");
memcpy(p_map, &temp, 1);
printf("after memcpyn");
shm_mat = shmdt(p_map);
if(shm_mat == -1){
printf("shmdt errorn");
return -1;
}
return 0;
}
编译通过,但是运行老出段错误,如下:
cc -o write write.c
$ ./write
key=8432
shmget=4
shmat -1
before memcpy
Segmentation Fault - core dumped
初步判断是memcpy处出错误,但是为什么会出错误,请指教?
#include
#include
#include
#include
#include
#include
int main()
{
int shm_id, shm_mat, i;
key_t key;
char temp;
char* p_map;
char* name = "/tmp/myshm2";
key = ftok(name, 0);
printf("key=%dn", key);
if(key == -1){
printf("ftok error");
return -1;
}
shm_id = shmget(key,4096,IPC_CREAT);
printf("shmget=%dn", shm_id);
if(shm_id == -1)
{
printf("shmget error");
return -1;
}
p_map = (char*)shmat(shm_id,NULL,0);
printf("shmat %dn", p_map);
temp = 'a';
printf("before memcpyn");
memcpy(p_map, &temp, 1);
printf("after memcpyn");
shm_mat = shmdt(p_map);
if(shm_mat == -1){
printf("shmdt errorn");
return -1;
}
return 0;
}
编译通过,但是运行老出段错误,如下:
cc -o write write.c
$ ./write
key=8432
shmget=4
shmat -1
before memcpy
Segmentation Fault - core dumped
初步判断是memcpy处出错误,但是为什么会出错误,请指教?
|
shmat调用出错了啊,所有返回的p_map为-1