正好用到了,记下来
1. 消息队列
首先要定义符合要求的struct
typedef struct{ int msg_type; char msg_data[128]; }MSG_DEF;
MSG_DEF send_msg; int key=8000, id; id = msgget(key, IPC_CREAT | 0660);//不存在就创建,存在就返回 msgsnd(id, &send_msg, sizeof(send_msg.msg_data), 0);
再来接收消息
MSG_DEF recv_msg; int key=8000, id; id = msgget(key, IPC_CREAT | 0660);//不存在就创建,存在就返回 msgrcv(id, &recv_msg, sizeof(recv_msg.msg_data), 0, IPC_NOWAIT);//非阻塞
2. 管道
这里关注有名管道
先发送,注意open时模式的选择(O_NONBLOCK),可能会导致open file:: No such device or address,具体原因未细究
#define FIFO_SERVER "my_fifo" unlink(FIFO_SERVER); if(mkfifo(FIFO_SERVER, O_CREAT | O_RDWR | 0666) != 0) perror("mkfifo:"); fd = open(FIFO_SERVER, O_WRONLY); if(fd< 0) perror("open file:"); ret = write(fd, filename, strlen(filename)); printf("send filename:[%s][%d]\n", filename, ret); close(fd);
再来接收
char filename[128] = {0}; int fd = 0; fd = open(FIFO_SERVER, O_RDONLY | O_NONBLOCK); read(fd, filename, sizeof(filename)); printf("recv filename:[%s]\n", filename); close(fd);