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 opr;
- void podnies(int semid, int semnum){
- opr.sem_num = semnum;
- opr.sem_op = 1;
- opr.sem_flg = 0;
- if (semop(semid, &opr, 1) == -1){
- perror("Podnoszenie semafora");
- exit(1);
- }
- }
- void opusc(int semid, int semnum){
- opr.sem_num = semnum;
- opr.sem_op = -1;
- opr.sem_flg = 0;
- if (semop(semid, &opr, 1) == -1){
- perror("Opuszczenie semafora");
- exit(1);
- }
- }
- void kasuj(char tab[])
- {
- int i=0;
- for(i; i<MAX; i++)
- {
- tab[i] = ' ';
- }
- }
- int main(){
- int shmid, semid, i;
- FILE *file;
- char *buf;
- char bufor[120];
- key_t key1;
- file = fopen("Puacz_pisarz.c", "r");
- if ((key1 = ftok(".", 'A')) == -1)
- errx(1, "Blad tworzenia klucza!");
- if (file != NULL) printf("Operacja otwarcia pliku powiodla sie\n");
- semid = semget(34170, 2, IPC_CREAT|0600);
- if (semid == -1){
- perror("Blad utworzenia tablicy semaforow");
- exit(1);
- }
- if (semctl(semid, 0, SETVAL, (int)1) == -1){
- perror("Blad nadania wartosci semaforowi 0");
- exit(1);
- }
- if (semctl(semid, 1, SETVAL, (int)0) == -1){
- perror("Blad nadania wartosci semaforowi 1");
- exit(1);
- }
- shmid = shmget(56392, MAX, IPC_CREAT|0600);
- if (shmid == -1){
- perror("Blad utworzenia segmentu pamieci wspoldzielonej");
- exit(1);
- }
- buf = shmat(shmid, NULL, 0);
- if (buf == NULL){
- perror("Blad przylaczenia segmentu pamieci wspoldzielonej");
- exit(1);
- }
- pid_t pid = fork();
- if(pid == 0) { // in child process
- while(1){
- if (buf[0] != '*') {
- //printf("PP1: %d : %d \n", getpid(), getppid());
- opusc(semid, 1);
- fflush(stdout);
- printf("PP1 PID: %d %s \n", getpid(), buf);
- fflush(stdout);
- podnies(semid, 0);
- }
- //exit(1);
- }
- }
- pid_t pidTWO = fork();
- if(pidTWO == 0) { // in child process
- while(1){
- if (buf[0] != '*') {
- //printf("PP1: %d : %d \n", getpid(), getppid());
- opusc(semid, 1);
- fflush(stdout);
- printf("PP2 PID: %d %s \n", getpid(), buf);
- fflush(stdout);
- podnies(semid, 0);
- }
- //exit(1);
- }
- }
- while(1) {
- char pin[50]; // przygotowanie tablicy charowej w celu odebrania znakow
- printf("Podaj ciag znakow:\n");
- scanf("%s", pin); // odbior znakow
- opusc(semid, 0);
- strcpy(buf, pin);
- podnies(semid, 1);
- kasuj(bufor);
- }
- exit(0);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement