Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Napisz cztery osobne programy. Każdy z nich powinien obsługiwać wybrany przez
- Ciebie sygna ł . Pierwszy z procesów b ę dzie co sekundę wysy ł a ł sygnał do drugiego
- procesu, drugi proces pod odebraniu sygna ł u powinien wypisać na ekranie
- komunikat, a nast ę pnie przes ł a ć sygnał do procesu trzeciego. Proces trzeci powinien
- zachowywać się podobnie jak drugi, a proces czwarty powinien jedynie wypisywać
- komunikat na ekranie. Odliczanie czasu w pierwszym procesie nale ż y zrealizować
- za pomoc ą SIGALARM.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <signal.h>
- #include <wait.h>
- #include <stdbool.h>
- volatile sig_atomic_t first_send_flag = false;
- volatile sig_atomic_t second_send_flag = false;
- volatile sig_atomic_t third_send_flag = false;
- void first_send_signal(int sig)
- {
- printf("Proces 1: Sygnal wyslany\n");
- first_send_flag = true;
- }
- void first_process(pid_t *pid)
- {
- if(signal(SIGALRM, first_send_signal) == SIG_ERR){
- perror("signal");
- exit(EXIT_FAILURE);
- }
- alarm(1);
- while(1){
- if(first_send_flag){
- kill((getpid()+1), SIGUSR1);
- first_send_flag = false;
- alarm(1);
- }
- }
- }
- void second_print_and_send(int sig)
- {
- printf("Proces 2: Sygnal otrzymany i przeslany dalej\n");
- second_send_flag = true;
- }
- void second_process(pid_t *pid)
- {
- if(signal(SIGUSR1, second_print_and_send) == SIG_ERR){
- perror("signal");
- exit(EXIT_FAILURE);
- }
- while(1){
- if(second_send_flag){
- kill((getpid()+1), SIGUSR1);
- second_send_flag = false;
- }
- }
- }
- void third_print_and_send(int sig)
- {
- printf("Proces 3: Sygnal otrzymany i przeslany dalej\n");
- third_send_flag = true;
- }
- void third_process(pid_t *pid)
- {
- if(signal(SIGUSR1, third_print_and_send) == SIG_ERR){
- perror("signal");
- exit(EXIT_FAILURE);
- }
- while(1){
- if(third_send_flag){
- kill((getpid()+1), SIGUSR1);
- third_send_flag = false;
- }
- }
- }
- void fourth_print(int sig)
- {
- if(sig == SIGUSR1)
- printf("Proces 4: Sygnal otrzymany\n\n");
- }
- void fourth_process(pid_t *pid)
- {
- if(signal(SIGUSR1, fourth_print) == SIG_ERR){
- perror("signal");
- exit(EXIT_FAILURE);
- }
- while(1){}
- }
- int main(void)
- {
- pid_t pid[4];
- for(int i = 0; i < 4; i++){
- usleep(100);
- pid[i] = fork();
- if(pid[i] == -1){
- perror("fork");
- return EXIT_FAILURE;
- }
- else if(pid[i] == 0){
- switch(i){
- case 0:
- first_process(pid);
- break;
- case 1:
- second_process(pid);
- break;
- case 2:
- third_process(pid);
- break;
- case 3:
- fourth_process(pid);
- break;
- default:
- return EXIT_FAILURE;
- }
- }
- else{
- waitpid(pid[3], NULL, 0);
- }
- }
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement