Skip to content

Instantly share code, notes, and snippets.

@markogresak
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save markogresak/1f192e10fb7a0f6f2c4b to your computer and use it in GitHub Desktop.

Select an option

Save markogresak/1f192e10fb7a0f6f2c4b to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
char sign;
int energy;
void timestamp() {
time_t ltime = time(NULL);
char *timeStr = asctime(localtime(&ltime));
timeStr[strlen(timeStr) - 1] = 0;
printf("[%s]: ", timeStr);
}
void changeSign() {
sign = sign == '.' ? '*' : '.';
}
void moreEnergy() {
energy += 10;
timestamp();
printf("Juhu! Nova energija! (%d).\n", energy);
}
void newProcess() {
int child = fork();
timestamp();
if(child == 0) {
sleep((energy % 7) + 1);
int status = (42 * energy) % 128;
printf("Izhodni status childa: %d\n", status);
exit(status);
}
else if(child > 0)
printf("PID fork childa: %d\n", child);
}
void killZombie() {
int status;
wait(&status);
if(WIFEXITED(status)) {
status = WEXITSTATUS(status);
timestamp();
printf("Status zombija: %d\n", status);
}
}
int main(int argc, char* argv[]) {
int demon = fork();
if(demon < 0) {
timestamp();
perror("Napaka pri forkanju! Demon se ni zagnal!");
return 0;
}
else if(demon > 0)
return 0;
dup2(1, 2);
freopen("lovec.log", "w", stdout);
signal(SIGTERM, moreEnergy);
signal(SIGUSR1, changeSign);
signal(SIGUSR2, newProcess);
signal(SIGCHLD, killZombie);
timestamp();
printf("PID: %d\n", getpid());
energy = argc == 1 ? 42 : atoi(argv[1]);
sign = '.';
while(energy > 0) {
printf("%c", sign);
fflush(0);
sleep(1);
energy--;
}
printf("\n");
timestamp();
printf("Out of energy!\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment