如何在Linux上运行以下消息队列?

时间:2018-07-02 12:46:24

标签: c linux process operating-system fork

银河帝国计划派遣一艘星际驱逐舰攻击反叛者的基地。该星驱逐舰将容纳1024名帝国克隆战士。

t=0,只有一名士兵可用:上尉。从他的第一个生日开始,克隆战士每年就可以克隆一次。领导者希望让星际驱逐舰在短时间内准备行动。

帝国命令结构非常简单:

  • 每个战士都向其克隆发送命令
  • 与上级没有联系

编写具有以下要求的Linux C程序:

  • 每个克隆战士都必须由一个单独的进程代表
  • 命令必须通过唯一(!)命名的消息队列进行传输 *从Imperator到队长已有一个消息队列/Imperator
  • 克隆阶段结束后,每个克隆战士都必须等待命令的接收并传递给下级

提示和要求:

  • 考虑一下,哪一年有多少士兵:t=0 –只是队长,t = 1 –队长和他的第一个克隆人,等等。
  • 不用担心错误处理

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h>
#include <sys/stat.h> 
#include <mqueue.h> 
#include <errno.h>

// Exercise „clone warriors“
#define NUM 10
#define SIZE_MSGBUF 500
#define MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH |S_IWOTH)

mqd_t QueueArray[NUM]; // queues to my clones
void cleanQueueArray(void) { // support function for init: start with no queues
    for (int i=0; i<NUM; i++) QueueArray[i] = 0;
}

int main(void) {
    char cNameBossQueue[100] = "/Imperator"; // boss queue‘s default name
    mqd_t BossQueue; // boss queue to receive commands of the father‘s process

    struct mq_attr attr;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = SIZE_MSGBUF;
    attr.mq_flags = 0;

    int nPrio=0;
    char cMsgbuf[SIZE_MSGBUF+1] = "";

    cleanQueueArray(); // init: no queues to any clones at the beginning

    // phase 1 / clone phase takes NUM years:
    for (int i=0; i<NUM; i++) {
        pid_t npid_child = fork();
        if (npid_child > 0) { // Father. Create + store command channel to clone:
            char cQueue[100];
            sprintf(cQueue, "/Queue%d", npid_child);
            QueueArray[i] = mq_open(cQueue, O_CREAT|O_WRONLY, MODE, &attr);
        } else { // Child. Remember the name of the boss queue:
            sprintf(cNameBossQueue, "/Queue%d", getpid());
            cleanQueueArray(); // Child has no queues to clones currently
        }
    }

    // Phase 2 / battle phase. Receive and transmit orders:
    BossQueue = mq_open(cNameBossQueue, O_RDONLY, MODE, &attr);
    mq_receive(BossQueue, cMsgbuf, SIZE_MSGBUF, &nPrio);

    // Send orders to all of my clones:
    for (int i=0; i<NUM; i++) {
        if (QueueArray[i] > 0) {
            mq_send (QueueArray[i], cMsgbuf, strlen(cMsgbuf), 0);
        }
    }

    // Cleanup work...
    return 0;
}

我尝试使用

gcc -o Wall clonew clonew.c -lrt"
./clonew

但是我没有输出

1 个答案:

答案 0 :(得分:0)

您的命令行(不包含结尾的",我认为这是发车事故)

gcc -o Wall clonew clonew.c -lrt

表示

  • 编译clonew和clonew.c
  • 放入名为“ Wall”的可执行文件
  • 使用rt lib

我不确定为什么使用“ clonew”(首先在编译命令中,然后在执行尝试中)不会触发任何警告。 显然,您打算创建并执行该文件。但是它用作输入文件,即使存在但不是C语法文件,也应该引起一些抱怨。

但是,尝试执行clonew时未获得预期输出的原因是您的compile命令不能导致创建可执行的clonew。

为什么尝试执行尚不存在或为C代码文件的操作不会导致任何警告,错误或任何其他输出都是一个谜。

如果它已经作为可执行文件但无提示程序存在,它也应该引发投诉。

相关问题