Last active
August 29, 2015 14:13
-
-
Save markogresak/1f192e10fb7a0f6f2c4b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <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(<ime)); | |
| 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