简单迭代服务器
头文件
myhead.h
#ifndef MYHEAD_H_
#define MYHEAD_H_
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<mqueue.h>
#include<sys/msg.h>
#define MSG_R 0400
#define MSG_W 0200
#define SVMSG (MSG_R | MSG_W | MSG_R >> 3 | MSG_W >> 3)
#define MAXLINE 4096
#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP)
struct msgbuf
{
__syscall_slong_t mtype;
char mtext[1];
};
#define MQ_KEY1 1234L
#define MQ_KEY2 2345L
#endif
mesg.h
#ifndef MESG_H_
#define MESG_H_
#include"myhead.h"
#define MAXMESGDATA (MAXLINE-2*sizeof(long))
#define MESHDRSIZE (sizeof(struct mymsg) - MAXMESGDATA)
struct mymsg
{
long len;
long type;
char data[MAXLINE];
};
ssize_t mesg_send(int, struct mymsg*);
ssize_t mesg_recv(int, struct mymsg*);
#endif
客户端
client_main.c
#include"mesg.h"
void client(int, int);
int main(int argc, char**argv)
{
int readid, writeid;
readid = msgget(MQ_KEY2, 0);
writeid = msgget(MQ_KEY1, 0);
client(readid, writeid);
return 0;
}
client.c
#include"mesg.h"
void client(int readfd, int writefd)
{
struct mymsg msg;
ssize_t len = 0;
int ret = 0;
msg.type = 10;
fgets(msg.data,MAXLINE, stdin);
len = strlen(msg.data);
if(msg.data[len - 1] == '\n')
len--;
msg.len = len;
ret = mesg_send(writefd, &msg);
if(ret < 0)
perror("send error");
printf("send %s\n", msg.data);
sleep(1);
msg.type = 10;
while((len = mesg_recv(readfd, &msg)) >0)
{
puts(msg.data);
}
printf("client is over\n");
return;
}
服务端
server_main.c
#include"mesg.h"
void server(int, int);
int main(int argc, char**argv)
{
int readid, writeid;
readid = msgget(MQ_KEY1, IPC_CREAT | SVMSG);
writeid = msgget(MQ_KEY2, IPC_CREAT | SVMSG);
server(readid, writeid);
return 0;
}
server.c
#include"mesg.h"
void server(int readfd, int writefd)
{
char buff[MAXLINE] = {0};
ssize_t len = 0;
struct mymsg msg;
int fd = 0;
msg.type = 10;
while(1)
{
printf("here\n");
len = mesg_recv(readfd, &msg);
msg.data[len] = '\0';
mesg_send(writefd, &msg);
fd = open(msg.data, O_RDONLY | O_NONBLOCK);
msg.type = 10;
while((len = read(fd, msg.data, MAXLINE)) > 0)
{
msg.len = len;
mesg_send(writefd, &msg);
}
printf("file %s send over, closing it\n", msg.data);
close(fd);
}
return;
}