linux C-(进程间通信 消息队列)

来源:互联网 发布:360浏览器mac版百度云 编辑:程序博客网 时间:2024/04/29 21:38

以下是自己的原创....转载请注明出处,,,,,谢谢哈

linux 引入消息队列的原因是,实现对紧急事件的处理。可以为消息设置优先级

下面是一个共享消息队列的例子,在linux2.6的内核中能够运行,通过消息队列实现进程间的通信,可以自己选择优先级,本列优先级设置为子进程自己的PID....2.6中能够运行,,,,,,,,

#include<stdio.h>
#include<sys/msg.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<string.h>
#define MAXLINE 4096
int main()
{
int msqid;

int pid ;
struct msgbuf
{
   long mtype;
   char mtext[MAXLINE];
};
if(-1 == (msqid = msgget(IPC_PRIVATE,IPC_EXCL)))
{
   perror("msgget error:");
   return 0;
};
if((pid = fork()) < 0)
{
   perror("fork error:");
   return 0;
}
else if(pid == 0)
{
   /*in child*/
   struct msgbuf buf;
   struct msqid_ds bf;
   buf.mtype = getpid(); /* this is mark the type of the mesage */
   strcpy(buf.mtext,"pid1 msg1..../n");
   if(-1 == msgsnd(msqid,&buf,MAXLINE,IPC_NOWAIT))
   {
    perror("megsnd error:");
    return 0;
   }
   strcpy(buf.mtext,"pid1 msg2..../n");
   if(-1 == msgsnd(msqid,&buf,MAXLINE,IPC_NOWAIT))
   {
    perror("megsnd error:");
    return 0;
   }
   printf("%d/n",getpid());
   sleep(1);
   return 0;
}
else
{
   int pid2;
   if((pid2 = fork()) < 0)
   {
    perror("fork error:");
    return 0;
   }
   else if(pid2 == 0)
   {
    struct msgbuf buf;
    struct msqid_ds bf;
    sleep(1);
    buf.mtype = getpid(); /* this is mark the type of the mesage */
    strcpy(buf.mtext,"pid2 message/n");
    if(-1 == msgsnd(msqid,&buf,MAXLINE,IPC_NOWAIT))
    {
     perror("megsnd error:");
     return 0;
    }
    printf("%d/n",getpid());
    return 0;
   }
   else
   {
    char buf1[100];
    struct msgbuf buf;
    struct msqid_ds bf;
    sleep(2);
    if(-1 == msgrcv(msqid,&buf,MAXLINE,pid,IPC_NOWAIT))
    {
     perror("megrcv error");
     return 0;
    }

    printf(buf.mtext);
    if(-1 == msgrcv(msqid,&buf,MAXLINE,pid,IPC_NOWAIT))
    {
     perror("megrcv error");
     return 0;
    }
    printf(buf.mtext);
    printf("/n%d/n",buf.mtype);
    if(-1 == msgrcv(msqid,&buf,MAXLINE,0,IPC_NOWAIT))
    {
     perror("megrcv error");
     return 0;
    }
    printf(buf.mtext);
    printf("/n%d/n",buf.mtype);
    if(-1 == msgctl(msqid,IPC_RMID,&bf)) /* only one times erorr */
    {
     perror("IPC_RMID error:");
     return 0;
    }
    return 0;
   }
}
return 0;
}