信号队列实现随时通信
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
#include <signal.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/ipc.h>
//这是一个发送接受
struct msgbuf//需要的结构体
{
long mtype;
char mtext[128];
};
void* send(void* arg)//把消息发给对方,参数是队列号的地址
{
struct msgbuf buf;
int* p=(int*)arg;//使用指针存储队列号地址
while (1)
{
printf("请输入数据\n");
buf.mtype=1;//给对方发类型为1点数据包
fgets(buf.mtext,sizeof(buf.mtext),stdin);//定义数据消息准备发出去
buf.mtext[strlen(buf.mtext)-1]='\0';//因为最后一位总是'\0',所以也可以代替字符串清空操作
msgsnd(*p,(void*)&buf,sizeof(buf.mtext),0);//把定义好的结构体包发送,这个包有类型,有字符串数据
if(strcmp(buf.mtext,"quit")==0)//如果消息是quit,先发送给对面,然后自己杀死自己进程
{
kill(getpid(),2);
}
}
}
void* recive(void* arg)
{
struct msgbuf buf;
int* p=(int*)arg;//队列号地址指针
while (1)
{
memset(buf.mtext,0,sizeof(buf.mtext));//读取钱清空字符串
msgrcv(*p,(void*)&buf,sizeof(buf.mtext),2,0);//只接受类型为2的数据包,这个类型的数据包是对方给的,按顺序取出正确类型的数据包
if(strcmp(buf.mtext,"quit")==0)//如果接收到quit,说明对面离开了
{
printf("对方退出");
kill(getpid(),2);//杀死自己,收到对面quit,只剩下自己,只能也退出了
}
printf("对方的消息: %s\n",buf.mtext);
printf("请输入你的消息\n");
}
}
int main(char argc,char* argv[])
{
key_t key=ftok("./",89);
if(key<0)
{
perror("ftok");
return -1;
}
int m=msgget(key,IPC_CREAT|0777);
if(m<0)
{
perror("msgget");
return -1;
}
pthread_t tid1,tid2;
int res1=pthread_create(&tid1,NULL,send,(void*)&m);
int res2=pthread_create(&tid2,NULL,recive,(void*)&m);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
#include <signal.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/ipc.h>
struct msgbuf
{
long mtype;
char mtext[128];
};
void* send(void* arg)
{
struct msgbuf buf;
int* p=(int*)arg;
while (1)
{
printf("请输入数据\n");
buf.mtype=2;
fgets(buf.mtext,sizeof(buf.mtext),stdin);
buf.mtext[strlen(buf.mtext)-1]='\0';
msgsnd(*p,(void*)&buf,sizeof(buf.mtext),0);
if(strcmp(buf.mtext,"quit")==0)
{
kill(getpid(),2);
}
}
}
void* recive(void* arg)
{
struct msgbuf buf;
int* p=(int*)arg;
while (1)
{
memset(buf.mtext,0,sizeof(buf.mtext));
msgrcv(*p,(void*)&buf,sizeof(buf.mtext),1,0);
if(strcmp(buf.mtext,"quit")==0)
{
printf("对方退出");
kill(getpid(),2);
}
printf("对方的消息: %s\n",buf.mtext);
printf("请输入你的消息\n");
}
}
int main(char argc,char* argv[])
{
key_t key=ftok("./",89);
if(key<0)
{
perror("ftok");
return -1;
}
int m=msgget(key,IPC_CREAT|0777);
if(m<0)
{
perror("msgget");
return -1;
}
pthread_t tid1,tid2;
int res1=pthread_create(&tid1,NULL,send,(void*)&m);
int res2=pthread_create(&tid2,NULL,recive,(void*)&m);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}