1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <semaphore.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/types.h> #include <string.h> #include <strings.h> #include <fcntl.h>
#define fifo "/tmp/myfifo" #define string "myhelloworld"
int fd = 0; sem_t full, avail, mutex;
void *producer(void *arg) { sem_wait(&avail); sem_wait(&mutex); int ret = 0; int stringlen = strlen(string) + 1; int i = 0; while (i < 5) { ret = write(fd, string, stringlen); if (ret != stringlen) { printf("write string to fifo file error!\n"); pthread_exit(NULL); } printf("\nwrite string to fifo file successful!\n"); sem_post(&full); sem_post(&mutex); sleep(1); i++; } pthread_exit(NULL); }
void *consumer(void *arg) { sem_wait(&full); sem_wait(&mutex); int ret = 0; int stringlen = strlen(string) + 1; char buffer[stringlen]; bzero(buffer, stringlen); int i = 0; while (i < 5) { ret = read(fd, buffer, stringlen); if (ret != stringlen) { printf("read string from fifo file error!\n"); pthread_exit(NULL); } printf("read string from fifo:%s\n", buffer); bzero(buffer, stringlen); i++; sleep(1); sem_post(&avail); sem_post(&mutex); }
pthread_exit(NULL); }
int main(int argc, char **argv) { int ret; if (F_OK == access(fifo, 0)) { unlink(fifo); } ret = mkfifo(fifo, 0666); fd = open(fifo, O_RDWR); if (ret != 0) { perror("mkfifo"); } ret = sem_init(&full, 0, 0) + sem_init(&avail, 0, 1) + sem_init(&mutex, 0, 1); if (ret != 0) { printf("semphore init failed!\n"); } pthread_t threadid[2]; if (pthread_create(&threadid[0], NULL, producer, NULL) != 0) { printf("create thread failed!\n"); exit(EXIT_FAILURE); } if (pthread_create(&threadid[1], NULL, consumer, NULL) != 0) { printf("create thread failed!\n"); exit(EXIT_FAILURE); }
pthread_join(threadid[0], NULL); pthread_join(threadid[1], NULL); }
|