/* * producer.c * * Created on: 2011-11-19 * Author: snape */ #include <stdio.h> #include <sys/sem.h> #include <unistd.h> #include <stdlib.h> int main(int argc, char **argv) { void say(int, char*); int semid; struct sembuf buf; say((semid = semget(1000, 2, 0666)) < 0, "open semaphore 1000"); buf.sem_num = 0; buf.sem_op = -1; buf.sem_flg = buf.sem_flg & ~IPC_NOWAIT; say(semop(semid, &buf, 1) < 0, "P semaphore 1000 : 0"); fprintf(stderr, "[%d]producing...\n", getpid()); sleep(1); fprintf(stderr, "[%d]produced\n", getpid()); buf.sem_num = 1; buf.sem_op = 1; buf.sem_flg = buf.sem_flg & ~IPC_NOWAIT; say(semop(semid, &buf, 1) < 0, "V semaphore 1000 : 1"); return 0; } void say(int flag, char * str) { if (flag) { fprintf(stderr, "%s fail\n", str); exit(1); } else { fprintf(stderr, "%s success\n", str); } }
/* * consumer.c * * Created on: 2011-11-19 * Author: snape */ #include <stdio.h> #include <sys/sem.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char **argv) { void say(int, char*); int semid; struct sembuf buf; say((semid = semget(1000, 2, 0666)) < 0, "open semaphore 1000"); buf.sem_num = 1; buf.sem_op = -1; //设置操作方式为 阻塞 buf.sem_flg = buf.sem_flg & ~IPC_NOWAIT; say(semop(semid, &buf, 1) != 0, "P semaphore 1000:1"); fprintf(stderr, "[%d]consuming...\n", getpid()); sleep(1); fprintf(stderr, "[%d]consumed...\n", getpid()); buf.sem_num = 0; buf.sem_op = 1; buf.sem_flg = buf.sem_flg & ~IPC_NOWAIT; say(semop(semid, &buf, 1) != 0, "V semaphore 1000:0"); return 0; } void say(int flag, char * str) { if (flag) { fprintf(stderr, "%s fail\n", str); exit(1); } else { fprintf(stderr, "%s success\n", str); } }