通过共享内存共享阵列

时间:2018-08-29 01:19:06

标签: c

我有一个客户端/服务器程序。我正在读取一个文本文件,并将其存储在服务器程序中的数组中,我希望能够通过客户端程序进行访问。我正在努力了解如何使用客户端程序访问阵列。我已经看过strcpy(),memcpy()了,但我似乎还是想不起来。下面是客户端和服务器,以及我当前得到的输出。

服务器:

int main() {
    const key_t key = 12345678;
    FILE *ptr_fp;
    char words[600][600];
    char *mem;
    int i = 0;  
    ptr_fp = fopen("messages.txt","r");    

    int shmid = shmget(key, sizeof(float) * 8, 0644 | IPC_CREAT);

    if (shmid < 0) {
        perror("shmget");
        exit(1);
    } 

    printf("Created a shared memory segment of 32 bytes.\n");


    if (ptr_fp != NULL){
        while(fgets(words[i],600,ptr_fp )&& i <600){
            i++;
        }
    }

    mem = (char *)shmat(shmid,NULL,0);
    if(mem == (char *)-1){
        perror("shmat error\n");
        exit(1);
    } else {
        //strncpy(mem, words[0], sizeof(float)*8);
        printf("Memory is attached\n");
    }

    return 0;
}

客户端:

int main() {
    const key_t key = 12345678;
    char *mem,words[600][600];

    int shmid = shmget(key, sizeof(float) * 8, 0644);

    if (shmid < 0) {
        perror("shmget");
        exit(1);
    } 

    mem = (char *)shmat(shmid,NULL,0);
    if(mem == (char *)-1){
        perror("shmat error\n");
        exit(1);
    }

    for(int i = 0; words != NULL; i++){
        //printf("%s",words[i]);
    }

    return 0;
}

输出:

  

[1] 4330创建了一个32字节的共享内存段。记忆是   附上   CODE_CLI = 11; 01:su = 37; 41:sg = 30; 43:ca = 30; 41:tw = 30; 42:ow = 34 ; 42:st = 37; 44:ex = 01; 32: .tar = 01; 31: .tgz = 01; 31: .arj = 01; 31: .taz = 01; 31: .lzh = 01; 31: .lzma = 01; 31: .tlz = 01; 31: .txz = 01; 31:< em> .zip = 01; 31: .z = 01; 31: .Z = 01; 31: .dz = 01; 31: .gz = 01; 31 : .lz = 01; 31: .xz = 01; 31: .bz2 = 01; 31: .bz = 01; 31: .tbz = 01; 31: .tbz2 = 01; 31: .tz = 01; 31: .deb = 01; 31: .rpm = 01; 31:。 jar = 01; 31: .war = 01; 31: .ear = 01; 31: .sar = 01; 31: .rar = 01; 31: .ace = 01; 31: .zoo = 01; 31: .cpio = 01; 31: .7z = 01; 31: .rz = 01; 31 : .jpg = 01; 35: .jpeg = 01; 35: .gif = 01; 35: .bmp = 01; 35: .pbm = 01 ; 35: .pgm = 01; 35: .ppm = 01; 35: .tga = 01; 35: .xbm = 01; 35:。 xpm = 01; 35: .tif = 01; 35: .tiff = 01; 35: .png = 01; 35: .svg = 01; 35: .svgz = 01; 35: .mng = 01; 35: .pcx = 01; 35: .mov = 01; 35: .mpg = 01; 35: .mpeg = 01; 35: .m2v = 01; 35: .mkv = 01; 35: .webm = 01; 35: .ogm = 01 ; 35: .mp4 = 01; 35:。 m4v = 01; 35: .mp4v = 01; 35: .vob = 01; 35: .qt = 01; 35: .nuv = 01; 35: .wmv = 01; 35: .asf = 01; 35: .rm = 01; 35: .rmvb = 01; 35: .flc = 01; 35: .avi = 01; 35: .fli = 01; 35: .flv = 01; 35: .gl = 01; 35: .dl = 01 ; 35: .xcf = 01; 35: .xwd = 01; 35: .yuv = 01; 35: .cgm = 01; 35: .emf = 01; 35: .a [1] +   完成。/服务器       分段错误(核心已转储)

0 个答案:

没有答案