semaphore 2

sesame·2022년 2월 13일
0

교육

목록 보기
30/46

main.c

#include "th.h"

int main(int argc, char *argv[]){
        key_t key = 12345;
        pthread_t thread;
        char *shared_memory;
        char sndmsg[BUFFER_SIZE];
        char rcvmsg[BUFFER_SIZE];

        create_shm(key, BUFFER_SIZE);
        sem_init(&sem_one, 0, 0);
        sem_init(&sem_two, 0, 1);

        thread = create_thread(thread, sub_thread);
        sleep(1);

        while(1){
                sem_wait(&sem_two);  //1 -> 0

                strcpy(sndmsg, input_msg());

                if(!strlen(sndmsg)){
                        printf("no command\n");
                        continue;
                }

                shared_memory = at_shm(shmid);
                sprintf(shared_memory, "%s", sndmsg);

                //printf("main, name: %s\n", shared_memory);

                sem_post(&sem_one);  //0 -> 1
                sem_wait(&sem_two);

                if(!strcmp(sndmsg, "exit")){
                        sleep(1);
                        break;
                }

                //printf("main2, stat: %s\n", shared_memory);

                output_msg(shared_memory, sndmsg);
                sem_post(&sem_two);
        }

        rmv_shm(shmid);

        join_thread(thread);

        sem_destroy(&sem_one);
        sem_destroy(&sem_two);

        exit(0);
}

void *sub_thread(void *command){
        struct stat statbuf;
        char *shared_memory;

        pthread_t tid;

        tid = pthread_self();
        printf("[tid]: %lx\n", tid);

        while(1){
                sem_wait(&sem_one);  //1 -> 0

                shared_memory = at_shm(shmid);

                //printf("1sub, name: %s\n\n", shared_memory);

                if(!strcmp(shared_memory, "exit")){
                        sem_post(&sem_two); //0 -> 1
                        break;
                }

                sprintf(shared_memory, "%s", stat_name(shared_memory));
                //printf("2sub, name: %s\n\n", shared_memory);

                sem_post(&sem_two); //0 -> 1
        }
}

shm.c

#include "th.h"

void create_shm(key_t key, size_t size){
        shmid = shmget(key, size, 0666|IPC_CREAT|IPC_EXCL);
        if (shmid == -1){
                perror("shmget failed : ");
                exit(0);
        }
}

char *at_shm(int shmid){
        char *shared_memory;
        shared_memory = shmat(shmid, (void *)0, 0);
        if (shared_memory == (void *)-1){
                perror("shmat failed : ");
                exit(0);
        }
        return shared_memory;
}

void rmv_shm(int shmid){
        printf("rmv %d\n", shmid);
        if(shmctl(shmid,IPC_RMID, NULL) == -1){
                printf("shmctl failed\n");
        }
}

0개의 댓글