常用函数
#include
int shmget (key_t key, size_t size, int shmflg);
void* shmat (int shmid, const void* shmaddr,int shmflg);
int shmdt (const void* shmaddr);
int shmctl (int shmid, int cmd, struct shmid_ds* buf);
例子
server
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
char *ptrr = NULL;
char *ptrw = NULL;
pid_t cid;
bool first = true;
int shmidr;
int shmidw;
void sigint_proc(int sig){
if(ptrr != NULL){
if(first){
sscanf(ptrr,"%d",&cid);
printf("client pid:%d\n",cid);
first = false;
}else{
printf("recv:%s",ptrr);
}
}
}
void sigquit_proc(int sig){
shmdt(ptrr);
shmdt(ptrw);
shmctl(shmidr,IPC_RMID,NULL);
shmctl(shmidw,IPC_RMID,NULL);
exit(0);
}
int main(){
printf("进程号:%d\n",getpid());
if(signal(SIGINT,sigint_proc)==SIG_ERR){
perror("signal");
return -1;
}
if(signal(SIGQUIT,sigquit_proc)==SIG_ERR){
perror("signal");
return -1;
}
key_t id1 = ftok(".",100);
key_t id2 = ftok(".",101);
if(id1==-1 || id2==-1){
perror("ftok");
return -1;
}
shmidw = shmget(id1,4096,IPC_CREAT|0644);
shmidr = shmget(id2,4096,IPC_CREAT|0644);
if(shmidw == -1 || shmidr == -1){
perror("shmget");
return -1;
}
ptrw = shmat(shmidw,NULL,0);
if(ptrw == NULL){
perror("shmat");
return -1;
}
ptrr = shmat(shmidr,NULL,0);
if(ptrr == NULL){
perror("shmat");
return -1;
}
sprintf(ptrw,"%d",getpid());
for(;;){
if(!first){
fgets(ptrw,4096,stdin);
kill(cid,SIGINT);
}
}
return 0;
}
client
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
char *ptrr = NULL;
char *ptrw = NULL;
pid_t sid;
int shmidr;
int shmidw;
void sigint_proc(int sig){
if(ptrr != NULL){
printf("recv:%s",ptrr);
}
}
void sigquit_proc(int sig){
shmdt(ptrr);
shmdt(ptrw);
exit(0);
}
int main(){
printf("进程号:%d\n",getpid());
if(signal(SIGINT,sigint_proc)==SIG_ERR){
perror("signal");
return -1;
}
if(signal(SIGQUIT,sigquit_proc)==SIG_ERR){
perror("signal");
return -1;
}
key_t id1 = ftok(".",100);
key_t id2 = ftok(".",101);
if(id1==-1 || id2==-1){
perror("ftok");
return -1;
}
shmidr = shmget(id1,4096,0);
shmidw = shmget(id2,4096,0);
if(shmidw == -1 || shmidr == -1){
perror("shmget");
return -1;
}
ptrw = shmat(shmidw,NULL,0);
if(ptrw == NULL){
perror("shmat");
return -1;
}
ptrr = shmat(shmidr,NULL,0);
if(ptrr == NULL){
perror("shmat");
return -1;
}
sscanf(ptrr,"%d",&sid);
printf("server pid:%d\n",sid);
sprintf(ptrw,"%d",getpid());
kill(sid,SIGINT);
for(;;){
fgets(ptrw,4096,stdin);
kill(sid,SIGINT);
}
return 0;
}