码迷,mamicode.com
首页 > 其他好文 > 详细

System V实现的一个消息回射服务器与客户端

时间:2014-05-22 08:27:45      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:c   ext   a   int   get   string   

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实现的一个消息回射服务器与客户端,布布扣,bubuko.com

System V实现的一个消息回射服务器与客户端

标签:c   ext   a   int   get   string   

原文地址:http://blog.csdn.net/fuyuehua22/article/details/26140963

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!