Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Napisz program, który podzieli się na dwa procesy komunikuj ą ce się przy
- pomocy potoków. Komunikacja musi by ć dwukierunkowa.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <wait.h>
- #include <fcntl.h>
- #include <signal.h>
- #include <string.h>
- #include <stdbool.h>
- #define BUFFER_SIZE 128
- volatile sig_atomic_t send_flag = false;
- void send_handler(int signum)
- {
- send_flag = true;
- }
- int main(void)
- {
- int fdcp[2]; // children --> parent
- int fdpc[2]; // parent --> children
- pid_t pid;
- char buffer[BUFFER_SIZE];
- memset(buffer, '\0', BUFFER_SIZE);
- if((pipe(fdcp) == -1) || (pipe(fdpc) == -1)){
- perror("pipe");
- return EXIT_FAILURE;
- }
- if(signal(SIGUSR1, send_handler) == SIG_ERR){
- perror("signal");
- return EXIT_FAILURE;
- }
- pid = fork();
- if(pid == -1){
- perror("fork");
- return EXIT_FAILURE;
- }
- else if(pid == 0){
- // Wyslij wiadomosc
- printf("Potomek: Podaj wiadomosc do przeslania: ");
- fgets(buffer, BUFFER_SIZE, stdin);
- if(write(fdcp[1], buffer, BUFFER_SIZE) == -1){
- perror("write");
- return EXIT_FAILURE;
- }
- if(close(fdcp[1]) == -1){
- perror("close");
- return EXIT_FAILURE;
- }
- if(kill(getppid(), SIGUSR1) == -1){
- perror("kill");
- return EXIT_FAILURE;
- }
- // Poczekaj i odbierz wiadomosc
- while(!send_flag)
- ;
- send_flag = false;
- memset(buffer, '\0', BUFFER_SIZE);
- if(read(fdpc[0], buffer, BUFFER_SIZE) == -1){
- perror("read");
- return EXIT_FAILURE;
- }
- printf("Potomek: Przeslana wiadomosc: %s\n", buffer);
- if(close(fdpc[0]) == -1){
- perror("close");
- return EXIT_FAILURE;
- }
- }
- else{
- // Poczekaj i odbierz wiadomosc
- while(!send_flag)
- ;
- send_flag = false;
- if(read(fdcp[0], buffer, BUFFER_SIZE) == -1){
- perror("read");
- return EXIT_FAILURE;
- }
- printf("Rodzic: Przeslana wiadomosc: %s\n", buffer);
- if(close(fdcp[0]) == -1){
- perror("close");
- return EXIT_FAILURE;
- }
- // Wyslij
- printf("Rodzic: Podaj wiadomosc do przeslania: ");
- memset(buffer, '\0', BUFFER_SIZE);
- fgets(buffer, BUFFER_SIZE, stdin);
- if(write(fdpc[1], buffer, BUFFER_SIZE) == -1){
- perror("write");
- return EXIT_FAILURE;
- }
- if(close(fdpc[1]) == -1){
- perror("close");
- return EXIT_FAILURE;
- }
- if(kill(pid, SIGUSR1) == -1){
- perror("kill");
- return EXIT_FAILURE;
- }
- wait(NULL);
- }
- return EXIT_SUCCESS;
- }
Add Comment
Please, Sign In to add comment