Sunday, 7 October 2012

Two unrelated programs uses shared memory

First program


#include<stdio.h>
#include<sys/shm.h>
#include<string.h>
int main()
{

int id=shmget(17,50,0666|IPC_CREAT);


if(id>=0)
{
printf("\nShared memory created with id:%d\n",id);
}
char *adr=shmat(id,NULL,0);
if(adr>=0)
printf("Memory attached\n");
printf("Enter a string\n");
char str[10];

scanf("%s",str);
strncpy(adr,str,sizeof(str));



}



Second program

#include<stdio.h>
#include<sys/shm.h>
#include<string.h>
int main()
{

int id=shmget(17,0,0666|IPC_CREAT);
char str[10];

if(id>=0)
{
printf("\nShared memory with id:%d\n is accessed",id);
}
char *adr=shmat(id,NULL,0);
if(adr>=0)
printf("\nMemory attached\n");
printf("\nThe string is\n%s",adr);
}


Sample output:

cc first.c
./a.out

Shared memory created with id:360454
Memory attached
Enter a string
Hello

cc second.c
./a.out

Shared memory with id:360454
 is accessed
Memory attached

The string is
hello


0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More