共享内存实现进程间通信

#include "stdio.h"
#include "string.h"
#include "unistd.h"
#include "sys/shm.h"
 
int main()
{
    int id = shmget(0x8888, 100, IPC_CREAT|0644);
    if (id==-1)
    {
        perror("Error");
        return -1;
    }
    char *p = shmat(id, NULL, 0);
    if (p == ((char*)-1))
    {
        perror("Error");
        return -1;
    }
    strcpy(p, "Hello Shared Memory!");
    shmdt(p);
 
    return 0;
}
 
 
#include "stdio.h"
#include "string.h"
#include "unistd.h"
#include "sys/shm.h"
 
int main()
{
    int id = shmget(0x8888, 0, 0);
    if (id==-1)
    {
        perror("get Error");
        return -1;
    }
    char *p = shmat(id, NULL, SHM_RDONLY);
    if ( p == ((char*)-1))
    {
        perror("At Error");
        return -1;
    }
    puts(p);
    shmdt(p);
    shmctl(id, IPC_RMID, 0);
    return 0;
}
posted on 2014-12-30 16:23  张武亮  阅读(240)  评论(0编辑  收藏  举报