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 <stdlib.h>
- #include <mqueue.h>
- #define PROCESS_COUNT 10
- struct my_msgbuf {
- long mtype;
- int marker;
- };
- struct sembuf sops[2];
- struct my_msgbuf mqbuf;
- int semid,msqid;
- void child(int procnum);
- int main(){
- int pid,i;
- int flg = 0600 | IPC_CREAT;
- key_t skey = 999, mkey=888;
- mqbuf.mtype = 1;
- mqbuf.marker = 0;
- /* create a semaphore set with 10 semaphore: */
- if ((semid = semget(skey, PROCESS_COUNT, flg)) == -1) {
- perror("semget");
- exit(1);
- }
- if ((msqid = msgget(mkey, flg)) == -1) {
- perror("msgget");
- exit(1);
- }
- printf("Go...\n");
- for(i = 0; i < PROCESS_COUNT; i++){
- /*locks the semaphore*/
- sops[0].sem_num = i;
- sops[0].sem_op = 1;
- if (semop(semid, sops, 1) == -1) {
- perror("semop");
- exit(1);
- }
- printf("Parent sem %d locked\n",i);
- pid = fork();
- if(pid == 0){
- child(i);
- exit(1);
- }
- }
- printf("Parent sent message\n");
- if (msgsnd(msqid, &mqbuf, sizeof(mqbuf), 0) == -1)
- perror("msgsnd");
- for(i = 0; i < PROCESS_COUNT; i++){
- printf("Parent sem %d unlocked\n",i);
- /*unlcok*/
- sops[0].sem_num = i;
- sops[0].sem_op = -1;
- /*wait for child to finish*/
- sops[1].sem_num = i;
- sops[1].sem_op = 0;
- if (semop(semid, sops, 2) == -1) {
- perror("semop");
- exit(1);
- }
- /*lock*/
- printf("Parent sem %d wait\n",i);
- }
- wait();
- if (msgrcv(msqid, &mqbuf, sizeof(mqbuf), 0, 0) == -1) {
- perror("msgrcv");
- exit(1);
- }
- printf("Result %d\n",mqbuf.marker);
- /* remove sem and mq*/
- if (semctl(semid, 0, IPC_RMID) == -1) {
- perror("semctl");
- exit(1);
- }
- if (msgctl(msqid, IPC_RMID, NULL) == -1) {
- perror("msgctl");
- exit(1);
- }
- return 0;
- }
- void child(int procnum){
- /*waits for unlocking*/
- sops[0].sem_num = procnum;
- sops[0].sem_op = 0;
- /*lock*/
- sops[1].sem_num = procnum;
- sops[1].sem_op = 1;
- printf("Child sem %d wait\n",procnum);
- if (semop(semid, sops, 2) == -1) {
- perror("semop");
- exit(1);
- }
- printf("Child sem locked %d\n",procnum);
- printf("Child %d receive message\n",procnum);
- if (msgrcv(msqid, &mqbuf, sizeof(mqbuf), 0, 0) == -1) {
- perror("msgrcv");
- exit(1);
- }
- mqbuf.marker +=2;
- printf("Child %d sent message\n",procnum);
- if (msgsnd(msqid, &mqbuf, sizeof(mqbuf), 0) == -1)
- perror("msgsnd");
- /*unlock*/
- sops[0].sem_op = -1;
- if (semop(semid, sops, 1) == -1) {
- perror("semop");
- exit(1);
- }
- printf("Child sem unlocked %d\n",procnum);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement