代码
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<string.h>
#include<sys/types.h>
#include<stdlib.h>
#ifdef L
#define M 'L'
char writer[]="Lucy" ;
#endif
#ifdef B
#define M 'B'
char writer[]="Bob" ;
#endif
#ifdef P
#define M 'P'
char writer[]="Peter" ;
#endif
typedef struct msg_my {
long mytype ;
char name[20];
char mtext[100];
} MSG;
int main(int argc ,char **argv) {
char buffer[120]="";
int msgid;
MSG msg;
key_t key;
key=ftok(".",0xFF);
if((msgid=msgget(key,IPC_CREAT|0666))<0) {
perror("msgid");
exit(1);
}
pid_t pid;
pid=fork();
if(pid<0) {
perror("fork");
} else if(pid==0)
{
while(1) {
printf("\r%s:",writer);
fflush(stdout);
fgets(buffer,sizeof(buffer),stdin);
buffer[strlen(buffer)-1]='\0';
if(buffer[0]=='L'||buffer[0]=='B'||buffer[0]=='P') {
msg.mytype=(long)buffer[0];
strcpy(msg.name,writer);
strcpy(msg.mtext,buffer);
msgsnd(msgid,&msg,sizeof(msg)-sizeof(long),0);
}
}
} else {
while(1) {
msgrcv(msgid,&msg,sizeof(msg)-sizeof(long),(long)(M),0);
printf("\r message from %s: %s\n",msg.name,msg.mtext);
printf("\r %s:",writer);
fflush(stdout);
}
}
return 0;
}
Makefile文件
all:6.1.c
gcc 6.1.c -o lucy -DL
gcc 6.1.c -o bob -DB
gcc 6.1.c -o peter -DP
clean:
rm lucy bob peter -f
运行结果(通过发送的消息首字母大写来判别消息发送给谁)
Bob发送消息和接收消息
Peter发送消息和接收消息
Lucy发送消息和接收消息