制片人和消费者 - 细分错误

时间:2017-04-12 04:24:09

标签: c producer-consumer

我是并发编程的初学者,我想实现一个消费者和制作人。我想从生产者两个整数后3秒钟发送,我想打印生产者的数字总和。

运行代码后我有Segmentation fault :(。 谢谢你的帮助:D

这是我的生产者代码:

#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);
}

在这里,我有消费者的代码:

#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;
}

0 个答案:

没有答案
相关问题