Startpunkten
This commit is contained in:
78
Lab1/lab1.c
Normal file
78
Lab1/lab1.c
Normal file
@@ -0,0 +1,78 @@
|
||||
/* ===========================================
|
||||
* Lab 1 i C & UNIX
|
||||
* ==========================================
|
||||
* Semaforer
|
||||
* ==========================================
|
||||
* Christian Ohlsson, di7chro@cse.kau.se
|
||||
* Karlstads universitet
|
||||
* 991110
|
||||
* ===========================================
|
||||
*/
|
||||
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#define WAITTIME 3
|
||||
#define PERMS 0000
|
||||
|
||||
int P(char *name){
|
||||
while(creat(name,PERMS) == -1) ;
|
||||
}
|
||||
void V(char *name){
|
||||
unlink(name);
|
||||
}
|
||||
void handleSig(){
|
||||
V("A");
|
||||
V("B");
|
||||
V("C");
|
||||
exit(0);
|
||||
}
|
||||
void A(){
|
||||
while(1) {
|
||||
P("A");
|
||||
write(1, "A", 1);
|
||||
V("B");
|
||||
sleep(WAITTIME);
|
||||
P("A");
|
||||
write(1, "A", 1);
|
||||
V("C");
|
||||
sleep(WAITTIME);
|
||||
}
|
||||
}
|
||||
void B(){
|
||||
while(1) {
|
||||
P("B");
|
||||
write(1, "B\n", 2);
|
||||
V("A");
|
||||
}
|
||||
}
|
||||
void C() {
|
||||
while(1) {
|
||||
P("C");
|
||||
write(1, "C\n", 2);
|
||||
V("A");
|
||||
}
|
||||
}
|
||||
int main() {
|
||||
int pidA, pidB, stat;
|
||||
if((signal(SIGINT, handleSig)) == SIG_ERR) {
|
||||
perror("\nCould not initialize signals\n");
|
||||
exit(0);
|
||||
}
|
||||
signal(SIGTERM, SIG_IGN);
|
||||
P("B");
|
||||
P("C");
|
||||
if((pidA=fork()) > 0) {
|
||||
if((pidB=fork()) > 0) {
|
||||
A();
|
||||
waitpid(pidA, &stat, 0);
|
||||
waitpid(pidB, &stat, 0);
|
||||
}
|
||||
if(pidB == 0)
|
||||
C();
|
||||
}
|
||||
if(pidA == 0)
|
||||
B();
|
||||
perror("\nCould not fork.\n");
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user