#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
struct msgbuf{
long type;
char buf[128];
};
int main(int argc, const char *argv[
{
if(argc != 2){
printf("参数数量错误\n");
return 1;
}
int msgtype = atoi(argv[1]);
// ① 获取秘钥
key_t key = ftok("./ipc",1);
if(key == -1){
perror("ftok");
return 1;
}
// ② 根据秘钥创建 / 访问消息队列
int id = msgget(key,IPC_CREAT |
if(id == -1){
perror("msgget");
return 1;
}
struct msgbuf msg;
int size = 0;
while(1){
memset(&msg,0,sizeof(msg));
msg.type = msgtype;//确认消息
printf("请输入:");
scanf("%128s",msg.buf);
while(getchar()!=10);
size = strlen(msg.buf);
msgsnd(id,&msg,size,0);
}
return 0;
}
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
struct msgbuf {
long type;
char buf[128];
};
int msgtype = 0;
int a=0;
void sig(int signum) {
if(a==0)
{
a=020000;
}
else
{
a=0;
}
printf("开始读取除指定编号为 %d 的消息外的所有消息\n",msgtype);
}
int main(int argc, const char *argv[]) {
if(argc != 2){
printf("参数数量错误\n");
return 1;
}
int msgtype = atoi(argv[1]);
key_t key = ftok("./ipc", 1);
if (key == -1) {
perror("ftok");
return 1;
}
int id = msgget(key, IPC_CREAT | 0666);
if (id == -1) {
perror("msgget");
return 1;
}
struct msgbuf msg;
signal(SIGINT, sig);
printf("开始读取所有消息\n");
while (1) {
memset(&msg, 0, sizeof(msg));
msgrcv(id, &msg, 128, msgtype, a);
printf("读取到的消息为:%s\n",msg.buf);
}
return 0;
}