Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/sem.h>
- #include <sys/shm.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <time.h>
- #include "header.h"
- int msggen(char *buf) {
- int length = rand() % (MSGSIZE - 2) + 1;
- int i;
- for(i = 0; i < length; ++i) {
- buf[i] = (char)(rand() % (END_CHAR - START_CHAR) + START_CHAR);
- }
- buf[length] = '\0';
- ++length;
- return length;
- }
- int detachSharedMem(void *attachedMem) {
- if(shmdt(attachedMem) == ERRCODE) {
- perror("shmdt");
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
- int delSharedMem(int sharedMem) {
- if(shmctl(sharedMem, IPC_RMID, NULL) == ERRCODE) {
- perror("shmctl");
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
- int delSem(int sem) {
- if(semctl(sem, DUMMY, IPC_RMID, DUMMY) == ERRCODE) {
- perror("semctl");
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
- int produce(int sem, char *attachedMem) {
- struct sembuf waitReading = {SEM_PRODUCER, LOCK, SEM_UNDO};
- struct sembuf produced = {SEM_CONSUMER, UNLOCK, SEM_UNDO};
- int i;
- for(i = 0; i < MSGCOUNT; ++i) {
- msggen(attachedMem);
- printf("Send: %s\n", attachedMem);
- if(semop(sem, &produced, 1) == ERRCODE) {
- perror("semop");
- return EXIT_FAILURE;
- }
- if(semop(sem, &waitReading, 1) == ERRCODE) {
- perror("semop");
- return EXIT_FAILURE;
- }
- // sleep(1);
- }
- return EXIT_SUCCESS;
- }
- int main() {
- srand(time(NULL));
- key_t idKey = ftok("header.h", PROJECT_PREFIX);
- if(idKey == ERRCODE) {
- perror("ftok");
- return EXIT_FAILURE;
- }
- int sem = semget(idKey, SEMCOUNT, IPC_CREAT | ACCESS_RIGHTS);
- if(sem == ERRCODE) {
- perror("semget");
- return EXIT_FAILURE;
- }
- int sharedMem = shmget(idKey, MSGSIZE, IPC_CREAT | ACCESS_RIGHTS);
- if(sharedMem == ERRCODE) {
- perror("shmget");
- delSem(sem);
- return EXIT_FAILURE;
- }
- char *attachedMem = shmat(sharedMem, ANY_PLACE, NO_FLAGS);
- if(attachedMem == NULL) {
- delSem(sem);
- delSharedMem(sharedMem);
- perror("shmat");
- return EXIT_FAILURE;
- }
- if(produce(sem, attachedMem) != EXIT_SUCCESS) {
- delSem(sem);
- detachSharedMem(attachedMem);
- delSharedMem(sharedMem);
- return EXIT_FAILURE;
- }
- if(detachSharedMem(attachedMem) != EXIT_SUCCESS) {
- delSharedMem(sharedMem);
- delSem(sem);
- return EXIT_FAILURE;
- }
- if(delSharedMem(sharedMem) != EXIT_SUCCESS) {
- delSem(sem);
- return EXIT_FAILURE;
- }
- if(delSem(sem) != EXIT_SUCCESS) {
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement