Linux系统软中断和消息队列结合实现一发一收
直接放代码:
#include<stdio.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<sys/ipc.h>
#include<stdlib.h>
#include<string.h>
#include<signal.h>
#include<unistd.h>
#define MSGKEY 75
struct msgfrom{
long mtype;
char msgtext[1030];
}msg;
int msgqid,i;
void SERVER();
int state;
int m,n;
void CLIENT();
void stop()
{
state=0;
}
void waiting()
{
while(state!=0);
}
int main()
{
while((i=fork())==-1);
if(i>0)
{
SERVER();
}
else{
CLIENT();
}
wait(0);
wait(0);
}
void SERVER(){
msgqid=msgget(MSGKEY,0777|IPC_CREAT);
state=1;
signal(SIGINT,stop);
waiting();
do
{
msgrcv(msgqid,&msg,1030,0,0);
printf("(server)received message %d ",msg.mtype);
printf("%s",msg.msgtext);
kill(n,17);
}while(msg.mtype!=1);
msgctl(msgqid,IPC_RMID,0);
exit(0);
}
void CLIENT()
{
int i;
char string_i[50];
msgqid=msgget(MSGKEY,0777);
m=getppid();
n=getpid();
signal(SIGINT,SIG_IGN);
for(i=10;i>=1;i--)
{
msg.mtype=i;
printf("(client)sent\n");
sprintf(msg.msgtext,"the content of message is :");
sprintf(string_i,"message %d",i);
strcat(msg.msgtext,string_i);
strcat(msg.msgtext,"\n");
msgsnd(msgqid,&msg,1030,0);
state=1;
signal(17,stop);
waiting();
}
exit(0);
}
运行结果:
实现思路比较简单,还有很多方法可以实现。