linux环境编程进程间通信(共享内存)

/*****************************************
* name : shm_a.c
* author : cyher
* date : 2008-8-6
* description : 进程a,共享内存通信
*****************************************/
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

int
main()
{
int oflag,id;
char *ptr;
char buf[512];
size_t length=512;
time_t t;

oflag = 0644|IPC_CREAT;
id = shmget(ftok(“/home/cyher/workspace/c/star”,89),length,oflag);
if((ptr = shmat(id,NULL,0)) == (void *) -1)
{
perror(“shmat”);
exit(1);

}
while(1)
{
t=time(NULL);
memset(buf,0,512);
memcpy(buf,ptr,512);
printf(“%s”,buf);
sprintf(ptr,”time: %s pid: [%d]\n”,asctime(localtime(&t)),getpid());
sleep(5);
}
}

/*****************************************
* name : shm_b.c
* author : cyher
* date : 2008-8-6
* description : 进程b,共享内存通信
*****************************************/

#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

int
main()
{
int oflag,id;
char *ptr;
char buf[512];
size_t length=512;
time_t t;

oflag = 0644|IPC_CREAT;
id = shmget(ftok(“/home/cyher/workspace/c/star”,89),length,oflag);
if((ptr = shmat(id,NULL,0)) == (void *) -1)
{
perror(“shmat”);
exit(1);

}
while(1)
{
sleep(5);
t=time(NULL);
memset(buf,0,512);
memcpy(buf,ptr,512);
printf(“%s”,buf);
sprintf(ptr,”time: %s pid: [%d]\n”,asctime(localtime(&t)),getpid());
}
}

0 Responses to “linux环境编程进程间通信(共享内存)”


  • No Comments

Leave a Reply