Created
November 15, 2013 15:57
-
-
Save junfenglx/7486668 to your computer and use it in GitHub Desktop.
producer and consumer problem,process version.
using Posix mqueue.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <semaphore.h> | |
#include <fcntl.h> | |
#include <sys/stat.h> | |
#include <sys/wait.h> | |
#include <mqueue.h> | |
#define N 1 | |
#define BUFSIZE 1024 | |
#define LOOP 10*N | |
int main(int argc,char *argv) | |
{ | |
mqd_t mqd; | |
pid_t producerPid,consumerPid; | |
int flags=O_RDWR | O_CREAT | O_EXCL; | |
unsigned int prio=0; | |
//int flags=O_RDWR; | |
mode_t perms=0666; | |
struct mq_attr attr; | |
attr.mq_maxmsg=N; | |
attr.mq_msgsize=BUFSIZE; | |
mqd=mq_open("/mq",flags,perms,&attr); | |
if (mqd<0) | |
{ | |
printf("error on create mqueue.\n"); | |
exit(0); | |
} | |
mq_close(mqd); | |
if ((consumerPid=fork())<0) | |
{ | |
exit(1); | |
} | |
else if(consumerPid==0) | |
{ | |
//consumer | |
mqd=mq_open("/mq",O_RDONLY); | |
void *item=malloc(BUFSIZE); | |
for (int i=0;i<LOOP;++i) | |
{ | |
mq_receive(mqd,item,BUFSIZE,&prio); | |
printf("receive %d\n",(int)*(char*)(item)); | |
} | |
exit(0); | |
} | |
else | |
{ | |
if ((producerPid=fork())<0) | |
{ | |
exit(1); | |
} | |
else if (producerPid==0) | |
{ | |
//producer | |
char *item=(char*)malloc(sizeof(char)); | |
mqd=mq_open("/mq",O_WRONLY); | |
for (int i=0;i<LOOP;++i) | |
{ | |
*item=i%128; | |
printf("send %d\n",(int)(*item)); | |
mq_send(mqd,item,1,0); | |
} | |
exit(0); | |
} | |
else | |
{ | |
while(wait(NULL)!=-1) | |
continue; | |
mq_unlink("/mq"); | |
return 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment