0

I'm a beginner in concurrent programming and I want to implement a consumer and producer. I want to send after 3 seconds from producer two integers and I want to print the sum of numbers from producer.

After running the code I have Segmentation fault :(. Thank you for help :D

This is my code for producer:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define VECTOR_SIZE 2

struct msgbuf
{
    long    mtype;
    int     vector[VECTOR_SIZE];
};

int main() {
    int msqid;
    // int msgflg = IPC_CREAT | 0666;
    key_t key;
    struct msgbuf sbuf;
    size_t buflen;
    int i;

    key = ftok(".", 'g');

    //Get the message queue ID for the given key
    if ((msqid = msgget(key, IPC_CREAT | 0666 )) < 0) {
      perror("Could not get message queue\n");
      exit(1);
    }
    printf("MSQID value: %d\n", msqid);
    //Message Type
    sbuf.mtype = 1;
    while(1){
        for(i = 0; i < 2; i++){
            printf("Enter a message to add to message queue : ");
            scanf("%d",sbuf.vector[i]);

            buflen = strlen(sbuf.vector[i]) + 1 ;
        }
        sleep(3);
    }

    // getchar();

    if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)
    {
        printf ("%d, %ld, %d, %d\n", msqid, sbuf.mtype, sbuf.vector[0], sbuf.vector[1], (int)buflen);
        perror("Could not send message!\n");
        exit(1);
    }
    else
        printf("Message Sent\n");

    exit(0);
}

And here I have the code for consumer:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 128

#define VECTOR_SIZE 2

struct msgbuf
{
    long    mtype;
    char    vector[VECTOR_SIZE];
};
int main() {
  int msqid;
  key_t key;
  struct msgbuf rcvbuffer;

  // key = 1234;
  key = ftok(".", 'g');

  if ((msqid = msgget(key, 0666)) < 0) {
    perror("Could not get message queue\n");
    exit(1);
  }
  printf("MSQID value: %d\n", msqid);
  //  Receive an answer of message type 1.
  if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0) {
    perror("Could not receive message!\n");
    exit(1);
  }

  printf("%d\n", rcvbuffer.vector[0] + rcvbuffer.vector[1]);
  return 0;
}
Laurentiu
  • 39
  • 6
  • In producer you are using `strlen` on a integer i.e. `buflen = strlen(sbuf.vector[i]) + 1 ;` – kuro Apr 12 '17 at 04:41
  • Also in `scanf()` it should be `scanf("%d", &(sbuf.vector[i]));`. The address of `sbuf.vector[i]` – kuro Apr 12 '17 at 04:44
  • And the second last printf of the producer also contains more arguments than the format expects. 4 expected 5 given. – EmbedWise Apr 12 '17 at 04:47

0 Answers0