Linux下共享内存(shm)使用示例

#include <sys/ipc.h>  
#include <stdio.h>  
#include <sys/shm.h>  
#include <sys/types.h>  
#include <unistd.h>  
#include <string.h>  
#define PERM IPC_CREAT //S_IRUSR|S_IWUSR   
#include <errno.h>  
int main(int argc,char **argv)   
{   

    int shmid[2048];   
    char *p_addr,*c_addr;   
    if(argc!=2)   
    {   
        fprintf(stderr,"Usage:%s InputString\n\a",argv[0]);   
        return 1;   
    }   

    int i =0;  
    for ( i = 0; i<1024; i++ )  
    {  
        char *p = new char[1024*1024];  
        if ( NULL == p )  
        {  
            printf( "error new\n" );  
            return -1;  
        }  
    }  

    for ( i =0; i<1026; i++ )  
    {  
        if((shmid[i]=shmget(IPC_PRIVATE,/*1610612736*/ 1024*1024,PERM))==-1)   
        {   
            fprintf(stderr,"Create Share Memory Error:%s\n\a",strerror(errno));   
            return 1;   
        }   
        {   
            p_addr=(char*)shmat(shmid[i],0,0);   
            p_addr[0] = i/1000 + '0';  
            p_addr[1] = i%1000/100 + '0';  
            p_addr[2] = i%100/10 + '0';  
            p_addr[3] = i%10 + '0';  
            p_addr[4] = '\0';  
            printf( "%d, %s\n", i, p_addr );  
        }  
    }