指数增加C ++中的进程数

时间:2015-11-26 04:21:08

标签: c++ ipc message-passing

我正在编写一个应用程序,在C / C ++中的进程之间发送消息,这是我到目前为止的代码:

#include <sys/types.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <chrono>
#include <iostream>
#include <unistd.h>


#define MSGSZ 128

using namespace std;
using namespace std::chrono;

/*
 * Declare the message structure.
 */

typedef struct msgbufer {
    long    mtype;
    char    mtext[MSGSZ];
} message_buf;

int main()
{
    int msqid;
    int msgflg = IPC_CREAT | 0666;
    key_t key;
    message_buf sbuf;
    size_t buf_length;

    /*
     * Get the message queue id for the
     * "name" 1234, which was created by
     * the server.
     */
    key = 1234;

    (void) fprintf(stderr, "\nmsgget: Calling msgget(%i,\
%#o)\n",
                   key, msgflg);

    if ((msqid = msgget(key, msgflg )) < 0) {
        perror("msgget");
        exit(1);
    }
    else
        (void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid);


    /*
     * We'll send message type 1
     */

    sbuf.mtype = 1;


    (void) strcpy(sbuf.mtext, "Hello other process 2.");

    buf_length = strlen(sbuf.mtext) + 1 ;

    /*
     * Send a message.
     */

    high_resolution_clock::time_point t1 = high_resolution_clock::now();
    int err = msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT);
    high_resolution_clock::time_point t2 = high_resolution_clock::now();

    if (err < 0) {
        printf ("%d, %li, %s, %lu\n", msqid, sbuf.mtype, sbuf.mtext, buf_length);
        perror("msgsnd");
        exit(1);
    }

    else
        printf("Message: \"%s\" Sent\n", sbuf.mtext);

    auto duration = duration_cast<nanoseconds>( t2 - t1 ).count();

    cout << "Execution time 2: " << duration << endl;

    pid_t recProcess = fork();

    if(recProcess == 0){

        int msqid;
        key_t key;
        message_buf  rbuf;

        /*
         * Get the message queue id for the
         * "name" 1234, which was created by
         * the server.
         */
        key = 1234;

        if ((msqid = msgget(key, 0666)) < 0) {
            perror("msgget");
            exit(1);
        }


        /*
         * Receive an answer of message type 1.
         */
        if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) {
            perror("msgrcv");
            exit(1);
        }

        /*
         * Print the answer.
         */
        printf("Message recieved: %s\n", rbuf.mtext);

    }

    exit(0);
}

在这种情况下,我只有两个进程,一个发送消息,另一个接收它。 我需要增加发送和接收消息的进程数量,同时通过两个(例如2,4,8,16 ..)进程的功能在内存中向对方发送消息(例如,1个进程发送消息)而另一个收到它) 任何的想法?

0 个答案:

没有答案