1. 程式人生 > >簡單的訊息佇列例項

簡單的訊息佇列例項

服務端程式

**1.smd.h**
#ifndef UPGRADE_H
#define UPGRADE_H
#define MSG_MAX_SIZE        (24)

enum 
{
    HTTP_TYPE_UPLOAD = 0x0,
    HTTP_TYPE_DOWNLOAD
};

typedef struct _DownloadInfo
{
    char download_url[128];
    char save_path[32];
    char save_name[32];
}DownloadInfo;

enum 
{
    MSG_START_UPGRADE = 0x01
, MSG_STOP_UPGRADE }; struct msgbuf { long msg_type; char msg_text[MSG_MAX_SIZE]; }; enum { MSG_TYPE_START_WIFIDOG_SETUP = 0x01, MSG_TYPE_START_UPGRADE = 0x02, MSG_TYPE_START_PING_SVR_IP = 0x03 }; #endif **2.Makefile** EXEC = smd OBJS = main.o #CFLAGS += -L$(ROOTDIR)/user/openssl-0.9.8e -L.
CFLAGS += -L$(ROOTDIR)/lib/libnvram -lnvram -I$(ROOTDIR)/lib/libnvram all: $(EXEC) .c.o: $(CC) -c $(CFLAGS) $< $(EXEC): $(OBJS) $(CC) $(OBJS) $(CFLAGS) -o [email protected] romfs: $(ROMFSINST) /bin/smd clean: -rm -f $(EXEC) *.elf *.o **3.main.c** #include <stdio.h> #include <stdlib.h>
#include <string.h> #include <linux/reboot.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include "smd.h" #include "nvram.h" int main(int argc, char *argv[]) { int msg_id = 0; key_t key; struct msgbuf msg_buf; int nBytes = 0; key = ftok("/dev/null", 'u'); msg_id = msgget(key, IPC_CREAT|0666); if (msg_id < 0) { printf("msgget failed\n"); return -1; } while(1) { memset(&msg_buf, 0x0, sizeof(msg_buf)); msgrcv(msg_id, &msg_buf, MSG_MAX_SIZE, 0, IPC_NOWAIT); if (nBytes >= 0) { switch (msg_buf.msg_type) { case MSG_TYPE_START_WIFIDOG_SETUP: nvram_commit(RT2860_NVRAM); nvram_commit(RT2860_BAK); system("vwanip.sh"); system("wifimonitor.sh"); break; case MSG_TYPE_START_PING_SVR_IP: { char command[64] = {0x0}; snprintf(command, sizeof(command), "ping %s -c 5", msg_buf.msg_text); system(command); } break; case MSG_TYPE_START_UPGRADE: break; default: break; } } } return 0; }

客戶端程式:

/****/
int msg_id = 0;
key_t key;
struct msgbuf msg_buf;

memset(&msg_buf, 0x0, sizeof(msg_buf));
msg_buf.msg_type = MSG_TYPE_START_WIFIDOG_SETUP;

if (msgsnd(msg_id, (void *)&msg_buf, 0, 0) < 0) {
    return -1;
}

/****/
if (!strcmp(svr_cmd, CMD_DO_PING)) {
    /* start do the ping action  */
    memset(&msg_buf, 0x0, sizeof(msg_buf));
    msg_buf.msg_type = MSG_TYPE_START_PING_SVR_IP;
    strncpy(msg_buf.msg_text, svr_ip, sizeof(msg_buf.msg_text));
    if (msgsnd(msg_id, (void *)&msg_buf, sizeof(msg_buf.msg_text), 0) < 0) 
    {
        ret = -1;
    }
}