Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <math.h>
- #include <sys/time.h>
- #include <time.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <signal.h>
- #define CHILDREN_COUNT 2
- int childs[CHILDREN_COUNT];
- char *getCurrentTime();
- void childHandler(int sig);
- void parentHandler(int sig, siginfo_t *info, void *context);
- int main()
- {
- struct sigaction sa;
- sa.sa_flags = SA_SIGINFO;
- sa.sa_sigaction = parentHandler;
- sigaction(SIGUSR2, &sa, NULL);
- for (int i = 0; i < CHILDREN_COUNT; i++)
- {
- int pid = fork();
- childs[i] = pid;
- if (pid == 0)
- {
- signal(SIGUSR1, childHandler);
- for(int j = 0; j < 10; j++){
- printf("Child %d paused...\n", getpid());
- pause();
- }
- exit(0);
- }
- else if (pid > 0)
- {
- }
- else
- {
- printf("error");
- return -1;
- }
- }
- usleep(100);
- kill(childs[0], SIGUSR1);
- kill(childs[1], SIGUSR1);
- for(int j = 0; j < 10; j++){
- printf("Parent %d paused...\n", getpid());
- pause();
- }
- return 0;
- }
- void childHandler(int sig)
- {
- printf("Signal %d\n", sig);
- if (sig == SIGUSR1)
- {
- static int n = 1;
- printf("CHILD GET %d %d %d %s\n", n, getpid(), getppid(), getCurrentTime());
- usleep(100);
- printf("CHILD SEND %d %d %d %s\n", n, getpid(), getppid(), getCurrentTime());
- kill(getppid(), SIGUSR2);
- n++;
- }
- }
- void parentHandler(int sig, siginfo_t *info, void *context)
- {
- printf("Signal %d\n", sig);
- if (sig == SIGUSR2)
- {
- static int n = 1;
- printf("PARENT GET %d %d %d %s\n", n, getpid(), info->si_pid, getCurrentTime());
- usleep(100);
- printf("PARENT SEND %d %d %d %s\n", n, getpid(), info->si_pid, getCurrentTime());
- kill(info->si_pid, SIGUSR1);
- n++;
- }
- }
- char *getCurrentTime()
- {
- char buffer[15];
- char *current_time;
- int millisec;
- struct tm *tm_info;
- struct timeval tv;
- gettimeofday(&tv, NULL);
- millisec = lrint(tv.tv_usec / 1000.0); // Round to nearest millisec
- if (millisec >= 1000)
- { // Allow for rounding up to nearest second
- millisec -= 1000;
- tv.tv_sec++;
- }
- tm_info = localtime(&tv.tv_sec);
- strftime(buffer, 15, "%H:%M:%S", tm_info);
- current_time = (char *)malloc(20 * sizeof(char));
- sprintf(current_time, "%s:%03d\n", buffer, millisec);
- return current_time;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement