Implementing System V Message Queues and Semaphores in C

Computer science1.76 KB

PROGRAMA_ESCRITOR_COLA: IPC Implementation

The PROGRAMA_ESCRITOR_COLA reads an 80-character maximum name, an address, and a salary (long integer) until the word "FIN" is entered in the name field. This information is placed into a message queue along with a user-defined message type. While this program runs, it prevents other processes from accessing the message queue. Upon completion, the system allows up to two processes to simultaneously access the queue to extract messages.

Data Structure Definition

struct employee {
    long type;
    char name[80];
    char dir[80];
    long salary;
};

Implementation Logic

The program initializes the IPC mechanisms using ftok, semget, and msgget. It uses semaphores to ensure exclusive access during the writing phase and signals the reader processes upon completion.

main() {
    int semid, colaid, nb;
    struct employee hired;
    struct sembuf op;
    key_t key;

    if ((key = ftok("/", 'A')) == -1) {
        perror("Error creating key");
        return 1;
    }

    if ((semid = semget(key, 2, IPC_CREAT | 0666)) == -1) {
        perror("Failed to create semaphore");
        return 1;
    }

    if ((colaid = msgget(key, IPC_CREAT | 0666)) == -1) {
        perror("Error creating message queue");
        return 1;
    }

    if (semctl(semid, SESC, SETVAL, 1) == -1 || semctl(semid, SLEC, SETVAL, 0) == -1) {
        perror("Failed to initialize semaphore");
        return 1;
    }

    op.sem_num = SESC;
    op.sem_op = -1;
    op.sem_flg = 0;
    if (semop(semid, &op, 1) == -1) {
        perror("Failed to acquire semaphore writer");
    }

    puts("Enter name");
    // ... (Input loop and message queue logic follows)
}

Download

PDF Word HTML