linux环境编程之进程间通信(消息队列)

    /**************************************************************
* name : server.c                          *
* author : cyher                          *
* date : 2008-8-6                          *
* description : 服务端进程向消息队列里面放消息传给客户端     *
**************************************************************/
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <time.h>

struct msgbuf/*消息队列结构*/
{
    long mtype;
    char mtext[256];
};

int
init_daemon(void);/*守护进程启动函数*/

int
main()
{
    key_t key;
    int msgid;
    char *p;
    time_t t;
    struct msgbuf msg= {100,""};/*设置消息的id为100*/
    key = ftok("/home/cyher/workspace/c/star",'s');/*产生一个key*/
    msgid = msgget(key,IPC_CREAT | 0666);/*产生一个ipc标识*/
    if(msgid == -1)
    {
        perror("msgget");
        exit(1);
    }

    init_daemon();/*守护进程创建*/
    while(1)/*进入循环执行*/
    {
        t = time(NULL);
        p = asctime(localtime(&t));
        strcpy(msg.mtext,p);/*把时间字符放入msg.mtext*/
        msgsnd(msgid,&msg,strlen(msg.mtext)+1,IPC_NOWAIT);/*放入消息队列无阻塞*/
        sleep(2);
    }


   
}


/**************************************************************
* name : client.c                          *
* author : cyher                          *
* date : 2008-8-6                          *
* description : 客户端进程从消息队列里面取消息打印到屏幕上   *
**************************************************************/
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <time.h>

struct msgbuf
{
    long mtype;
    char mtext[256];
};

int
main()
{
    key_t key;
    int msgid;
    struct msgbuf msg;
    key = ftok("/home/cyher/workspace/c/star",'s');
    msgid = msgget(key,IPC_CREAT | 0666);
    if(msgid == -1)
    {
        perror("msgget");
        exit(1);
    }

    while(1)
    {
        if(msgrcv(msgid,&msg,256,100,IPC_NOWAIT) == -1)
        {
            perror("msgrcv:");
        }
        printf("%s",msg.mtext);
        memset(&msg,0,sizeof(struct msgbuf));
        sleep(2);
    }


   
}




/*******************************
* name:init_daemon.c
* author:cyher
* date:2008-8-1
* description:initialize a daemon process
* */

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>

int
init_daemon()
{
    int pid;
    int i;
    if( (pid=fork())<0 )
    {
        perror("fork");
        exit(1);
    }
    else if(pid > 0) //是父进程就退出
    {
        exit(0);
    }

    if((pid=fork()) < 0)
    {
        perror("fork2");
        exit(1);
    }
    else if (pid > 0)//是第一子进程也退出
    {
        exit(0);
    }
    //
    //下面都是第二子进程运行
    sleep(2);
    setsid();//使子进程脱离父进程的关系,把父进程的信息改掉
    //脱离终端的控制
    //
    for(i=0;i<1024;i++)//关闭文件描述符,节省资源
        close(i);
    chdir("/tmp");//改变工作目录
    umask(0);//重设掩码,使程序工作顺畅
   
    return 0;
   



}

posted @ 2008-11-23 13:06  冯赞锋  阅读(881)  评论(0)    收藏  举报