⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 读共享内存.txt

📁 读共享内存的c语言程序
💻 TXT
字号:
/* read information from shared memory */

#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>

#define PERM S_IRUSR|S_IWUSR
#define SIZE 512

/*typedef struct shmtype{*/      /* define the type of data stored in shmem */
    /*char name[4];*/
    /*int age;*/
/*}animal;*/

union semun{                /* define the union for the fuction semctl */
    int val;
    struct semid_ds * buf;
    ushort_t * array;
}sem;

int semcre(key_t key){      /* the function to creat the semaphore */
    union semun sem;
    int semid;
    sem.val=0;
    semid=semget(key,1,PERM);
    if(semid==-1){
        printf("Creat Semaphore Error!\n");
        exit(-1);
    }
    /*semctl(semid,0,SETVAL,sem);*/   /* initiate the semaphore */
    return semid;
}

void waitv(int semid){
    struct sembuf sops={0,0,0};
    semop(semid,&sops,1);
}

int main(int argc, char **argv){
    key_t key;
    int semid,shmid,reval,i;
    /*char * a;*/
    /*int buf[100];*/
       /*animal * shm;*/
    int   num  = 0;
    char * shm;
    char * pathname="/home/agent/src/ShMemCre.c";

    key=ftok(pathname,'a');
    if(key==-1){
        fprintf(stderr,"Creat Key Error:[%s]\n",strerror(errno));
        exit(-1);
    }

    shmid=shmget(key,SIZE,PERM);
    if(shmid==-1){
        fprintf(stderr,"Link share memory error:[%s]\n",strerror(errno));
        exit(-1);
    }

    /*shm=(animal *)shmat(shmid,0,0);*/
    shm=(char *)shmat(shmid,0,0);

    if(shm==(char *)-1){
        fprintf(stderr,"Attach Shared Memory Error:[%s]\n",strerror(errno));
        exit(-1);
   }

    printf("read from addr = [%x]\n",shm );
    semid=semcre(key);

    /*printf("shm data = [%s]\n",shm);*/

    num = atoi(argv[1]);
    for(i=num;i<=num+4;i++){
        waitv(semid);
        /*printf( "name:%s\n",(*(shm+i)).name );*/
        /*printf( "age: %d\n",(*(shm+i)).age );*/
        /*a=shm+i;*/
        printf("a=%d\n",*(shm+i));
    }

    if(shmdt(shm)==-1){
        printf("detach Shared Memory Error!\n");
        return -1;
    }
    return 0;
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -