linux 消息队列 epoll,Linux下进程通信–消息队列

代码

[cpp]

/*

* main.cc

*

* Created on: 2010-1-19

* Description: IPC–消息队列的实现

* Copyright: 2010 @ ICT Li Heyuan

*/

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

typedef struct {

long mtype;

char mtext[10];

} _msgbuf;

const char *path = "/tmp/test_ipc_1234";

int proj_id = 123;

int ret;

int main() {

//第零步 创建path这个文件

ret = creat(path, S_IRWXU);

if (ret == -1) {

printf("create file fail.\n");

exit(-1);

}

//第一步 获得key_t(System V key)

key_t key = ftok(path, ‘d’);

if (key == -1) {

printf("get key_t fail.\n");

exit(-1);

}

//第二步 创建一个message_queue

//这个|S_IRWXU是设置权限,同open的mode参数,最低8位决定

int msgid = msgget(key, IPC_CREAT | S_IRWXU);

if (msgid == -1) {

printf("create msg_queue fail:%s.\n", strerror(errno));

exit(-1);

}

ret = fork();

if (ret == -1) {

printf("fork fail.\n");

exit(-1);

} else if (ret == 0) {

printf("I’m child pid %d\n", getpid());

//第三步 子进程 发送msgsnd

_msgbuf msg1;

msg1.mtype = 4;

strcpy(msg1.mtext, "Hi");

ret = msgsnd(msgid, &msg1, sizeof(_msgbuf), 0);

if (ret == -1) {

printf("send msg fail:%s\n", strerror(errno));

} else {

printf("send msg success.\n");

}

exit(0);

} else {

//第四步 父进程 接受msgsnd

printf("I’m father pid %d\n", getpid());

_msgbuf msg1;

ssize_t size = msgrcv(msgid, &msg1, sizeof(msg1), 4, 0);

if (size == -1) {

printf("rcv msg fail.\n");

} else {

printf("Child send me a msg %d bytes,said:%s\n", size, msg1.mtext);

}

}

ret = msgctl(msgid, IPC_RMID, NULL);//删除消息队列

if (ret == -1) {

printf("unlink msg queue error\n");

exit(-1);

}

exit(0);

}

[/cpp]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值