<pre name="code" class="cpp">#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <time.h>
#include <unistd.h>
struct mymesg{
long type;
char data[512];
};
int err_sys(char *p);
void printfmsgds(struct msqid_ds ds)
{
//printf("msq_qnum = %d\n",ds.msq_qnum);
printf("msglen = %d\n", (int)(ds.msg_qbytes));
printf("msg_lspid = %d\n", ds.msg_lspid);
}
int main(int argc,char* argv[])
{
key_t key;
int qid;
pid_t pid;
struct ipc_perm ipcperm;
struct msqid_ds ds;
struct mymesg msg = {1,"hello\n"};
struct mymesg rmsg;
if( (key = ftok("/home/tsbirdman",163)) == (key_t)-1)
{
printf("error");
exit(-1);
}
if( (qid = msgget(key,IPC_CREAT | IPC_EXCL)) == -1)
{
printf("msgget error\n");
exit(-1);
}
if( (pid = fork()) < 0)
{
printf("fork error\n");
exit(-1);
}else if( pid == 0 )
{
sleep(1);
if( msgsnd(qid,&msg,7,0) == -1 )
{
printf("msgsnd error\n");
exit(-1);
}
exit(0);
}
//father process
waitpid(pid, NULL, 0);
if( msgrcv(qid, &rmsg, 7, 1, 0) == -1)
{
printf("msgrcv error\n");
exit(-1);
}
if( msgctl(qid, IPC_STAT, &ds) < 0)
{
printf("msgctl error\n");
exit(-1);
}
printf("receive msg = %s",rmsg.data);
printfmsgds(ds);
if( msgctl(qid, IPC_RMID, NULL) < 0)
err_sys("remove queue error\n");
exit(0);
}
int err_sys(char *p)
{
printf("erro: %s\n",p);
exit(-1);
}
linux消息队列实例
最新推荐文章于 2024-02-26 20:57:56 发布