Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <semaphore.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include <sys/sem.h>
- #include <sys/stat.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <string.h>
- #include <err.h>
- #include <unistd.h>
- #define MAX 50
- static struct sembuf semaphor; // deklaracja semafora
- void push(int, int); // podnoszenie
- void pop(int, int); // opuszczanie
- //--MAIN
- int main(){
- int shmid, semid;
- char* buf;
- //tworzenie tablicy semaforow
- semid = semget(34170, 2, IPC_CREAT | 0600);
- //nadawanie wartosci semaforowi
- semctl(semid, 0, SETVAL, (int) 1);
- semctl(semid, 1, SETVAL, (int) 0);
- //tworzenie segmentu pamieci wspoldzielonej
- shmid = shmget(56392, MAX, IPC_CREAT | 0600);
- // przylaczanie pamieci wspoldzielonej
- buf = shmat(shmid, NULL, 0);
- pid_t p1, p2, p3;
- // KONSUMENT 1
- if ((p1 = fork()) == 0) { // in child process
- while (1) {
- if (buf[0] != '/') {
- pop(semid, 1);
- fflush(stdout);
- printf("\tp1 PID: %d : %s \n", getpid(), buf);
- fflush(stdout);
- push(semid, 0);
- //push(semid, 1);
- }
- //exit(1);
- }
- }
- // KONSUMENT 2
- if ((p2 = fork()) == 0) {
- while (1) {
- if (buf[0] != '/') {
- pop(semid, 1);
- fflush(stdout);
- printf("\tp2 PID: %d : %s \n", getpid(), buf);
- fflush(stdout);
- push(semid, 0);
- }
- //exit(1);
- }
- }
- // KONSUMENT 3
- if ((p3 = fork()) == 0) {
- while (1) {
- if (buf[0] != '/') {
- pop(semid, 1);
- fflush(stdout);
- printf("\tp3 PID: %d : %s \n", getpid(), buf);
- fflush(stdout);
- push(semid, 0);
- }
- //exit(1);
- }
- }
- int i=0;
- //-- PRODUCENT
- for(;;){
- char input[50];
- if(i==0){
- printf("p0 %d produkt:", getpid());
- scanf("%s", input);
- }
- pop(semid, 0);
- if(i==1){
- printf("p0 %d produkt:", getpid());
- scanf("%s", input);
- }
- strcpy(buf, input);
- push(semid, 1);
- i=1;
- }
- exit(0);
- }
- //--SEMAFORY
- void push(int semid, int semnum){
- semaphor.sem_flg=0; // flaga
- semaphor.sem_num=semnum; // numer
- semaphor.sem_op = 1; // operacja
- if(semop(semid, &semaphor, 1) == -1){
- printf("Semafor podniesiony");
- exit(1);
- }
- //else printf("ERROR push");
- }
- void pop(int semid, int semnum){
- semaphor.sem_flg=0; // flaga
- semaphor.sem_num=semnum; // numer
- semaphor.sem_op = -1; // operacja
- if(semop(semid, &semaphor, 1) == -1){
- printf("Semafor podniesiony");
- exit(1);
- }
- //else printf("ERROR pop");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement