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)


0 0
原创粉丝点击