简体   繁体   中英

shared memory programme is not working in c

There are two programs are there one is call server which put content in shared memory and other is client which received a content from shared memory both in both programs it is attached successfully with shared memory but data is not display in client side.

Client.c

#include<fcntl.h>
#include<sys/ipc.h>
#include<sys/shm.h>
void main(int argc,char * argv[])
{
     int shmid=shmget(124,70,0777);
     char * data;
     printf("%d\n",shmid);  
     data=shmat(shmid,0,0);
     printf("%s",data);
}

Server.c

#include<fcntl.h>
#include<sys/ipc.h>
#include<sys/shm.h>
void main(int argc,char * argv[])
{
    int shmid=shmget(124,70,0777|IPC_CREAT);
    char * data,*ptr;
    printf("%d\n",shmid);
    if((data=shmat(shmid,0,0))==(char *)-1);
    {
        printf("No attach\n");
    }
    ptr=data;
    memset(data,0,1024);
    printf("%s",data);
    char c[]="My name is milap pancholi";
    int i=0;
    for(i=0;i<sizeof(c);i++)
    {
        printf("%c",c[i]);
        data+=c[i];
    }
    printf("%s\n",ptr);
}

Your main problem is this:

data+=c[i];

This does pointer arithmetic, advancing data , not what you want at all. Replace it with:

data[i] = c[i];

Other issues:

  • main returns int , not void. Use int main() { ... } if you don't need the arguments count and values (to avoid warnings, which you should turn way up).
  • You're missing #include <stdio.h> for printf
  • You're missing #include <string.h> for memset

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM