operating-systems/lab1/v7/using_pause.c

56 lines
1.4 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
void wait_clocks(clock_t clocks_to_wait) {
const clock_t end = clock() + clocks_to_wait;
while (clock() < end);
}
struct ping_pong_data {
char const *name;
const pid_t pid_to_print;
const pid_t pid_to_send;
double delay_seconds;
};
int run_exchange(char const *name, pid_t pid_to_print, pid_t pid_to_send, int wait_first, double delay_seconds) {
const clock_t delay_clocks = (clock_t) (CLOCKS_PER_SEC * delay_seconds);
if (wait_first)
goto WAIT;
while (1) {
printf("[%s] Got signal\n", name);
printf("[%s] PID=%d\n", name, pid_to_print);
printf("[%s] Sleeping %lf seconds before sending signal\n", name, delay_seconds);
wait_clocks(delay_clocks);
printf("[%s] Sending signal\n", name);
kill(pid_to_send, SIGUSR1);
WAIT:
pause();
}
perror("Program interrupted");
return EXIT_SUCCESS;
}
void noop(int){
}
int main(void) {
signal(SIGUSR1, noop);
pid_t parent_pid = getpid();
pid_t child_pid = fork();
switch (child_pid) {
case -1:
perror("Failed to fork\n");
return EXIT_FAILURE;
case 0:
child_pid = getpid();
return run_exchange("c", parent_pid, parent_pid, 1, 2.5);
default:
return run_exchange("p", child_pid, child_pid, 0, 2.5);
}
}