消息队列练习题

题目:
要求进程A创建一条消息队列之后向进程B发送SIGUSR1信号,进程B收到该信号之后打开消息队列并把进程的PID作为消息写入到消息队列中,要求进程B在写入消息之后,发SIGUSR2信号给进程A,进程A收到该信号则从消息队列中读取消息并输出消息正文的内容。
进程A的代码:


// 构造用于接收消息队列的结构体
typedef struct msg_buf
{
    long mtype;
    int mtext;
} msgbuf_t;

int msg_id;
struct msg_buf msgbuf;
int a;

// 收到进程B发送的SIGUSR2信号后,从消息队列中读取消息并输出消息正文的内容
void sighandler(int)
{

    bzero(&msgbuf, sizeof(msgbuf_t));

    a = msgrcv(msg_id, &msgbuf, sizeof(msgbuf_t), 0, 0); // 默认阻塞
    printf("a= %d\n", a);
    if (-1 == a)
    {
        fprintf(stderr, "msgrcv fail,error = %d, %s\n", errno, strerror(errno));
    }

    // 输出读取到的值
    printf("this is what I read from message queue:%d\n", msgbuf.mtext);
}

int main()
{
    // 创建一个键值,供消息队列使用
    key_t key = ftok(".", 0xffffff01);

    // 创建一条消息队列
    msg_id = msgget(key, IPC_CREAT | 0644);
    if (-1 == msg_id)
    {
        // printf("here\n");
        fprintf(stderr, "msgget fail,error = %d, %s\n", errno, strerror(errno));
    }

    // 手动输入进程B的PID
    int Bpid = 0;
    printf("please input the PID of processB\n");
    scanf("%d", &Bpid);

    // 向进程B发送SIGUSR1信号
    kill(Bpid, SIGUSR1);

    // 将需要读取的msgbuf缓冲区清零
    bzero(&msgbuf, sizeof(msgbuf_t));

    // 等待进程B发送的SIGUSR2信号
    signal(SIGUSR2, sighandler);

    while (1)
        ;

    return 0;
}

进程B的代码:


// 构造用于接收消息队列的结构体
typedef struct msg_buf
{
    long mtype;
    int mtext;
} msgbuf_t;

int msg_id;
msgbuf_t msgbuf;
int Apid;
int a;

void sighandler(int)
{
    // 创建A创建消息队列所用的键值
    key_t key = ftok(".", 0xffffff01);

    // 打开进程A创建的消息队列
    msg_id = msgget(key, 0644);
    if (-1 == msg_id)
    {
        fprintf(stderr, "msgget fail,error = %d, %s\n", errno, strerror(errno));
    }

    //  将需要读取的msgbuf缓冲区清零
    bzero(&msgbuf, sizeof(msgbuf_t));
    msgbuf.mtype = 1;

    // 获取当前进程pid,并存入缓存区
    msgbuf.mtext = getpid();
    printf("this what I sent%d\n", msgbuf.mtext);
    printf("here111\n");

    // 将缓存区发送到消息队列
    a = msgsnd(msg_id, &msgbuf, sizeof(int), 0); // 默认阻塞
    printf("a= %d\n", a);
    if (-1 == a)
    {
        printf("here\n");
        fprintf(stderr, "msgget fail,error = %d, %s\n", errno, strerror(errno));
    }

    printf("please input the PID of processA\n");
    scanf("%d", &Apid);

    // 发SIGUSR2信号给进程A
    kill(Apid, SIGUSR2);
}

int main()
{

    // 接收进程A发送的SIGUSR1信号
    signal(SIGUSR1, sighandler);

    while (1)
        ;

    return 0;
}
posted @ 2024-05-27 21:39  Dazz_24  阅读(44)  评论(0)    收藏  举报