Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <signal.h>
- #define createProc(parent, child) \
- if (currProc == parent) { \
- pid##child = fork(); \
- if (pid##child == 0) { \
- pid##child = getpid();\
- currProc = child; \
- } \
- }
- int currProc;
- int sendCount_1, sendCount_2;
- int receiveCount_1, receiveCount_2;
- pid_t pid1, pid2, pid3, pid4, pid5, pid6, pid7, pid8;
- void USR1_handler(int sig) {
- receiveCount_1++;
- }
- void USR2_handler(int sig) {
- receiveCount_2++;
- }
- void SIGTERM_handler(int sig) {
- printf("\n\nПроцесс: %d, pid: %d, ppid: %d остановился. Отправил %d usr1 и %d usr2\n\n", currProc, getpid(), getppid(), sendCount_1, sendCount_2);
- if (currProc != 1) {
- kill(getpid(), SIGKILL);
- }
- else {
- pid_t childPid = 0;
- while (childPid != -1) {
- childPid = wait(NULL);
- }
- exit(0);
- }
- }
- void printStat() {
- if (currProc == 1 || currProc == 5 || currProc == 6 || currProc == 7 || currProc == 8) {
- printf("\nПроцесс: %d, pid: %d, ppid: %d. Отправил %d USR1 и получил %d USR1. Time: %d", currProc, getpid(), getppid(), sendCount_1, receiveCount_1, time(NULL));
- }
- else if (currProc == 2) {
- printf("\nПроцесс: %d, pid: %d, ppid: %d. Отправил %d USR2 и получил %d USR1. Time: %d", currProc, getpid(), getppid(), sendCount_2, receiveCount_1, time(NULL));
- }
- else if (currProc == 3 || currProc == 4) {
- printf("\nПроцесс: %d, pid: %d, ppid: %d. Отправил %d USR1 и получил %d USR2. Time: %d", currProc, getpid(), getppid(), sendCount_1, receiveCount_2, time(NULL));
- }
- }
- void send(int proc, int sig, int groupId, int* counter) {
- if (currProc == proc) {
- while (*counter != 101) {
- kill(groupId, sig);
- (*counter)++;
- printStat();
- }
- printf("\n\nПроцесс: %d, pid: %d, ppid: %d остановился. Отправил %d usr1 и %d usr2\n\n", currProc, getpid(), getppid(), sendCount_1, sendCount_2);
- kill(groupId, SIGTERM);
- exit(0);
- }
- }
- int main() {
- signal(SIGUSR1, USR1_handler);
- signal(SIGUSR2, USR2_handler);
- signal(SIGTERM, SIGTERM_handler);
- createProc(0, 1);
- createProc(1, 2);
- createProc(2, 3);
- createProc(2, 4);
- createProc(4, 5);
- createProc(3, 6);
- createProc(6, 7);
- createProc(7, 8);
- sleep(1);
- if (currProc == 2) {
- setpgid(pid3, pid3);
- setpgid(pid4, pid3);
- }
- sleep(1);
- send(1, SIGUSR1, pid2, &sendCount_1);
- send(2, SIGUSR2, pid3, &sendCount_2);
- send(4, SIGUSR1, pid5, &sendCount_1);
- send(3, SIGUSR1, pid6, &sendCount_1);
- send(6, SIGUSR1, pid7, &sendCount_1);
- send(7, SIGUSR1, pid8, &sendCount_1);
- send(8, SIGUSR1, pid1, &sendCount_1);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement