共有メモリによるプロセス間通信の実現
3525 ワード
server.c #include "sys/types.h"
#include
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
#include "sys/shm.h"
#include "string.h"
struct mybuf{
int pid;
char buf[128];
};
void fun(int sigunm){
return;
}
int main(){
int shmid;
struct mybuf * p;
int pid;
int key;
key=ftok("./a.c",'a');
if(key<0){
printf("create key failure
");
return -1;
}
printf("create key success");
shmid=shmget(key,128,IPC_CREAT|0777);//
if(shmid<0){
printf("create share memory failure
");
return -1;
}
printf("create share memory success shime=%d
",shmid);
signal(SIGUSR1,fun);// SIGUSER2
p=(struct mybuf * )shmat(shmid,NULL,0);//
if(p==NULL){
printf("shmat function failure
");
return -3;
}
// pid
p->pid=getpid();
pause();// client read server pid;
pid=p->pid;
while(1){
printf("parent process start write share memory:
");
fgets(p->buf,128,stdin);//
kill(pid,SIGUSR2);// SIGUSER1 client pid
printf("send SIGUSR2 pid=%d, buf=%s",pid,p->buf);
pause();//
}
shmdt(p);
shmctl(shmid,IPC_RMID,NULL);
system("ipcs -m ");
return 0;
}
client.c
#include "sys/types.h"
#include
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
#include "sys/shm.h"
#include "string.h"
struct mybuf{
int pid;
char buf[128];
};
void fun(int sigunm){
return;
}
int main(){
int shmid;
struct mybuf * p;
int pid;
int key;
key=ftok("./a.c",'a');
if(key<0){
printf("create key failure
");
return -1;
}
printf("create key success");
shmid=shmget(key,128,IPC_CREAT|0777);//
if(shmid<0){
printf("create share memory failure
");
return -1;
}
printf("create share memory success shime=%d
",shmid);
signal(SIGUSR2,fun);// SIGUSER2
p=(struct mybuf * )shmat(shmid,NULL,0);//
if(p==NULL){
printf("shmat function failure
");
return -3;
}
// server pid
pid=p->pid;//read memory
//write client pid to share memory
p->pid=getpid();
//kill signal
kill(pid,SIGUSR1);
printf("server pid=%d lient pid=%d",pid,p->pid);
//clitent start read data from memery
while(1){
pause();//waite server write data
printf("client process receve data:%s
send to server pid=%d",p->buf,pid);
kill(pid,SIGUSR1);// SIGUSER1 server write memory
}
shmdt(p);
shmctl(shmid,IPC_RMID,NULL);
system("ipcs -m ");
return 0;
}