#include <sys/shm.h>
#include <sys/ipc.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define IPCKEY 0x366378
int test_share_mem_write()
{
int shm_id;
key_t key;
void * p_sm = 0;
int i_ret = 0;
shm_id = shmget(IPCKEY , 1028, IPC_CREAT | 0640); //obtain a shared memory identifier
if (-1 == shm_id)
{
printf("shmget error %d\n", shm_id);
exit(1);
}
p_sm = shmat(shm_id, (void*)0, 0); //a process attaches it to its address space
if (p_sm == (void*)-1)
{
printf("shmat error\n");
exit(1);
}
strncpy((char*)p_sm, "aaaaaaaa", sizeof(p_sm));
strncpy((char*)p_sm, "bbbbb", sizeof(p_sm));
i_ret = shmdt(p_sm); //detach the shared memory from process
if (i_ret == -1)
{
printf("shmdt error\n");
exit(1);
}
if (-1 == shmctl(shm_id, IPC_RMID, NULL)) // shmctl catchall for various shared memory operations, IPC_RMID is del
{
printf("shmctl IPC_RMID error\n");
exit(1);
}
return 0;
}
int main()
{
printf("hello share_mem_write\n");
test_share_mem_write();
}