System V实现的一个消息回射服务器与客户端
来源:互联网 发布:js return false 无效 编辑:程序博客网 时间:2024/05/17 02:05
echocli.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
#define MSGMAX 8192
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[MSGMAX]; /* message data */
};
void echo_cli(int msgid)
{
int n;
int pid;
pid = getpid();
struct msgbuf msg;
memset(&msg, 0, sizeof(msg));
*((int*)msg.mtext) = pid;
while (fgets(msg.mtext+4, MSGMAX, stdin) != NULL)
{
msg.mtype = 1;
if (msgsnd(msgid, &msg, 4+strlen(msg.mtext+4), 0) < 0)
ERR_EXIT("msgsnd");
memset(msg.mtext+4, 0, MSGMAX-4);
if ((n = msgrcv(msgid, &msg, MSGMAX, pid, 0)) < 0)
ERR_EXIT("msgsnd");
fputs(msg.mtext+4, stdout);
memset(msg.mtext+4, 0, MSGMAX-4);
}
}
int main(int argc, char *argv[])
{
int msgid;
msgid = msgget(1234, 0);
if (msgid == -1)
ERR_EXIT("msgget");
echo_cli(msgid);
return 0;
}
echosrv.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
#define MSGMAX 8192
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[MSGMAX]; /* message data */
};
void echo_srv(int msgid)
{
int n;
struct msgbuf msg;
memset(&msg, 0, sizeof(msg));
while (1)
{
if ((n = msgrcv(msgid, &msg, MSGMAX, 1, 0)) < 0)
ERR_EXIT("msgsnd");
int pid;
pid = *((int*)msg.mtext);
fputs(msg.mtext+4, stdout);
msg.mtype = pid;
msgsnd(msgid, &msg, n, 0);
}
}
int main(int argc, char *argv[])
{
int msgid;
msgid = msgget(1234, IPC_CREAT | 0666);
if (msgid == -1)
ERR_EXIT("msgget");
echo_srv(msgid);
return 0;
}
makefile:
.PHONY:clean all
CC=gcc
CFLAGS=-Wall -g
BIN=echosrv echocli
all:$(BIN)
%.o:%.c
$(CC) $(CFLAGS) -c $< -o $@
clean:
rm -f *.o $(BIN)
- System V实现的一个消息回射服务器与客户端
- 用一个消息队列(System V)实现客户端-服务器端
- System V消息队列实现服务器
- linux网络编程之System V 消息队列:消息队列实现回射客户/服务器和 msgsnd、msgrcv 函数
- posix消息队列与system v消息队列的区别
- linux网络编程之System V 消息队列(二):消息队列实现回射客户/服务器和 msgsnd、msgrcv 函数
- linux网络编程之System V 消息队列(二):消息队列实现回射客户/服务器和 msgsnd、msgrcv 函数
- System V 消息队列(多个客户和一个服务器)
- 用Java实现一个简单的服务器与客户端程序
- 用Java实现一个简单的服务器与客户端程序
- 一个简单的消息队列类(封装system V消息队列)
- System V的消息队列(1)
- system V 消息队列的用法
- system V消息队列的使用
- system v 消息队列
- System V 消息队列
- system v--消息队列
- System V消息队列
- 根据Excel进程ID销毁Excel进程
- c++托管使用c#动态库
- C#控制Word,Excel修改(复制、更改内容)、打印、保存权限
- 毕业了
- 设计模式入门之装饰器模式Decorator
- System V实现的一个消息回射服务器与客户端
- CSS+DIV集中问题
- 百度之星资格赛1001Energy Conversion
- 读书
- 使用response.getWriter().write() 乱码问题
- 我在兰亭这三年之部门动荡
- 单片机直流电机驱动电路
- 2014年百度之星程序设计大赛 Energy Conversion
- leetcode? Single Number II