linux消息队列实例,linux消息队列实例

#include 

#include

#include

#include

#include

#include

#include

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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值