该client和server能达到的基本功能是保证client发出的消息能够从server端接收并在屏幕上显示。要保证server能够接收client的消息,就必须保证server的生成的msg的不标识符是一样的,也就是两个用的key是必须一样的。 这对于我的移动IPv6中的消息传送已经足够了!:)
local.h
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#define SEED 'g'
#define SERVER 1L
#define BUFFERSIZE 1024
typedef struct {
long msg_to;
long msg_fm;
char buffer[BUFFERSIZE];
}MESSAGE;
client.c
#include "local.h"
main(void)
{
key_t key;
pid_t cli_pid;
int mid, n;
MESSAGE msg;
static char m_key[10];
cli_pid = getpid();
if((key = ftok(".",SEED)) == -1){
perror("Client:key generation");
exit(1);
}
/*Create Messg queue*/
if((mid = msgget(key, 0)) == -1){
mid = msgget(key, IPC_CREAT| 0660);
switch(fork()){
case -1:
perror("Client:fork");
exit(3);
case 0: //child process Added program later
;
break;
}
}
//parent process
while(1){
msg.msg_to =SERVER;//long int ,value is 1
msg.msg_fm = cli_pid;
write(fileno(stdout), "cmd>",4);
memset(msg.buffer, 0x0, BUFFERSIZE);
n = read(fileno(stdin), msg.buffer, BUFFERSIZE);
if(n == 0)
break;
if(msgsnd(mid, &msg, sizeof(msg), 0) == -1){
perror("Client: msgsend");
exit(5);
}
}
//delete msg queue
msgsnd(mid, &msg, 0, 0);
exit(0);
}
server.c
#include "local.h"
main(void)
{
int mid,n;
key_t key;
MESSAGE msg;
//Use the Same key with Client
if((key = ftok(".", SEED)) == -1){
perror("Client : key generation");
exit(1);
}
mid = msgget(key, IPC_CREAT | 0660);
while(1){
if((n = msgrcv(mid, &msg, sizeof(msg), SERVER,0)) == -1){
perror("SERVER:msgrcv");
exit(2);
}
else if (n==0)//client have finished
break;
else{
write(fileno(stdout),msg.buffer, strlen(msg.buffer));
}
}
msgctl(mid, IPC_RMID, (struct msqid_ds *)0);
exit(0);
}