Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <signal.h>
- #include <sys/time.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, sendCount_3;
- int receiveCount_1, receiveCount_2;
- pid_t pid1, pid2, pid3, pid4, pid5, pid6, pid7, pid8;
- long long currentTime() {
- struct timeval time;
- gettimeofday(&time, NULL);
- return time.tv_usec / 1000;
- }
- void USR1_handler() {
- receiveCount_1++;
- }
- void USR2_handler() {
- 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: %lld", currProc, getpid(), getppid(), sendCount_1, receiveCount_1, currentTime());
- }
- else if (currProc == 2) {
- printf("\nПроцесс: %d, pid: %d, ppid: %d. Отправил %d USR2 и получил %d USR1. Time: %lld", currProc, getpid(), getppid(), sendCount_2, receiveCount_1, currentTime());
- }
- else if (currProc == 3 || currProc == 4) {
- printf("\nПроцесс: %d, pid: %d, ppid: %d. Отправил %d USR1 и получил %d USR2. Time: %lld", currProc, getpid(), getppid(), sendCount_1, receiveCount_2, currentTime());
- }
- }
- 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(1, 3);
- createProc(1, 4);
- createProc(2, 5);
- createProc(2, 6);
- createProc(6, 7);
- createProc(7, 8);
- sleep(1);
- if (currProc == 1) {
- setpgid(pid2, pid2);
- setpgid(pid3, pid2);
- setpgid(pid4, pid2);
- }
- if (currProc == 2) {
- setpgid(pid5, pid5);
- setpgid(pid6, pid5);
- }
- sleep(1);
- send(1, SIGUSR1, pid2, &sendCount_2);
- send(2, SIGUSR2, pid5, &sendCount_2);
- send(6, SIGUSR1, pid7, &sendCount_1);
- send(7, SIGUSR1, pid8, &sendCount_1);
- send(8, SIGUSR2, pid1, &sendCount_1);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement