-
-
Save stetro/2869003 to your computer and use it in GitHub Desktop.
Piss Pott mit raceconditions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/ipc.h> | |
#include <sys/shm.h> | |
#include <sys/wait.h> | |
#define MAXCOUNT ((FUSS_B+FUSS_A)*17) | |
#define FUSS_B 15.51337 | |
#define FUSS_A 13.13123 | |
#define SEG_SIZE sizeof(double) | |
#define SHM_ERROR "Shared Memory konnte nicht erstellt werden!" | |
#define FORK_ERROR "fork() konnte keinen Kindprozess erzeugen!" | |
int main(int argc, char * argv[]) | |
{ | |
/* Hilfsvariablen*/ | |
int i, sleep_time; | |
if(argc <= 1) | |
{ | |
fprintf(stderr,"Zeit in us angeben !\n"); | |
return EXIT_FAILURE; | |
} | |
sleep_time = strtol(argv[1],NULL,10); | |
/* PIDs der Kindprozesse*/ | |
int pid[2]; | |
/* Shared Memory generieren und bei Fehlern aussteigen*/ | |
double *area,id; | |
id = shmget( IPC_PRIVATE, SEG_SIZE,0600); | |
if(id == -1) | |
{ | |
fprintf(stderr,SHM_ERROR); | |
return EXIT_FAILURE; | |
} | |
area = (double*)shmat(id,0,0); | |
if(area == NULL) | |
{ | |
fprintf(stderr,SHM_ERROR); | |
return EXIT_FAILURE; | |
} | |
/* Bereich zuruecksetzen*/ | |
*area = MAXCOUNT; | |
/* 1 Kindprozesse erzeugen*/ | |
pid[0] = fork(); | |
if(pid[0] == -1) | |
{ | |
fprintf(stderr,FORK_ERROR); | |
return EXIT_FAILURE; | |
} | |
if(pid[0] == 0) /* KIND 1*/ | |
{ | |
while(*area > 0) | |
{ | |
*area -= FUSS_A; | |
printf("POTT - %lf\n",*area); | |
fflush(stdout); | |
usleep(sleep_time); | |
} | |
return EXIT_SUCCESS; | |
} | |
else | |
{ | |
/* 2 Kindprozesse erzeugen*/ | |
pid[1] = fork(); | |
if(pid[1] == -1) | |
{ | |
fprintf(stderr,FORK_ERROR); | |
return EXIT_FAILURE; | |
} | |
if(pid[1] == 0) /* KIND 2*/ | |
{ | |
while(*area > 0) | |
{ | |
*area -= FUSS_B; | |
printf("PISS - %lf\n",*area); | |
fflush(stdout); | |
usleep(sleep_time); | |
} | |
return EXIT_SUCCESS; | |
} | |
/* VATER wartet auf alle Kinder*/ | |
for(i=0;i<2;i++) | |
{ | |
waitpid(*(pid+i),NULL,0); | |
} | |
} | |
/* ENDE*/ | |
/* return EXIT_SUCCESS;*/ | |
if(*area < 0.1 && *area > -0.1) | |
{ | |
/* Shared Memory loesen*/ | |
shmdt(area); | |
shmctl(id, IPC_RMID, 0); | |
printf("OK\n"); | |
return EXIT_SUCCESS; | |
} | |
else | |
{ | |
/* Shared Memory loesen*/ | |
shmdt(area); | |
shmctl(id, IPC_RMID, 0); | |
printf("Nicht OK\n"); | |
return EXIT_FAILURE; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment