p11-13.c

来自「SUN Solaris8平台下进程间通信」· C语言 代码 · 共 37 行

C
37
字号
#include <stdlib.h>#include <stdio.h>#include <string.h>#include <unistd.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>#include "err_exit.h"struct my_msg {           /* 消息缓冲区结构类型定义 */    long int my_msg_type;    char text[BUFSIZ];};int main(void){    int running = 1;         int msgid;    struct my_msg msgbuf;    long int msg_to_receive = 0;    /* 按顺序接收消息 */    /* 创建\打开我们的消息队列 */    msgid = msgget((key_t)1234, 0666 | IPC_CREAT);    if (msgid == -1)         err_exit("msgget failed\n");    /* 从队列中反复接收消息,直至收到字符串"end" */    while(running) {        /* 按正常顺序、阻塞方式接收消息 */        if (msgrcv(msgid, (void *)&msgbuf, BUFSIZ, msg_to_receive, 0) == -1)            err_exit ("msgrcv failed\n");        printf("You wrote: %s", msgbuf.text);        /* 显示收到的消息 */        if (strncmp(msgbuf.text, "end", 3) == 0)            running = 0;    }    /* 删除消息队列 */    if (msgctl(msgid, IPC_RMID, 0) == -1)         err_exit("msgctl(IPC_RMID) failed\n");    exit(EXIT_SUCCESS);}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?