Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Napisz program, w którym komunikacja mi ę dzy spokrewnionymi procesami
- b ę dzie odbywa ł a się w jednym kierunku za pomocą łą cza nienazwanego,
- a w drugim za pomoc ą łą cza nazwanego.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <wait.h>
- #include <signal.h>
- #include <fcntl.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <string.h>
- #include <stdbool.h>
- #define BUFFER_SIZE 512
- #define FIFO_DIR "./fifo"
- volatile sig_atomic_t send_flag = false;
- void send_handler(int signum)
- {
- send_flag = true;
- }
- int main(void)
- {
- pid_t pid;
- int pipefd[2];
- int fifofd;
- char buffer[512];
- memset(buffer, '\0', BUFFER_SIZE);
- if(signal(SIGUSR1, send_handler) == SIG_ERR){
- perror("signal");
- return EXIT_FAILURE;
- }
- if(pipe(pipefd) == -1){
- perror("pipe");
- return EXIT_FAILURE;
- }
- if(mkfifo(FIFO_DIR, 0600) == -1){
- perror("mkfifo");
- return EXIT_FAILURE;
- }
- pid = fork();
- if(pid == -1){
- perror("fork");
- return EXIT_FAILURE;
- }
- else if(pid == 0){
- // Wyslij
- printf("Podaj wiadomosc do wyslania laczem nienazwanym: ");
- fgets(buffer, BUFFER_SIZE, stdin);
- if(write(pipefd[1], buffer, BUFFER_SIZE) == -1){
- perror("write");
- return EXIT_FAILURE;
- }
- if(close(pipefd[1]) == -1){
- perror("close");
- return EXIT_FAILURE;
- }
- if(kill(getppid(), SIGUSR1) == -1){
- perror("kill");
- return EXIT_FAILURE;
- }
- // Odbierz
- while(!send_flag)
- ;
- send_flag = false;
- memset(buffer, '\0', BUFFER_SIZE);
- if((fifofd = open(FIFO_DIR, O_RDONLY)) == -1){
- perror("fifofd");
- return EXIT_FAILURE;
- }
- if(read(fifofd, buffer, BUFFER_SIZE) == -1){
- perror("read");
- return EXIT_FAILURE;
- }
- if(close(fifofd) == -1){
- perror("close");
- return EXIT_FAILURE;
- }
- printf("Przeslana wiadomosc: %s\n", buffer);
- }
- else{
- // Odbierz
- while(!send_flag)
- ;
- send_flag = false;
- if(read(pipefd[0], buffer, BUFFER_SIZE) == -1){
- perror("read");
- return EXIT_FAILURE;
- }
- if(close(pipefd[0]) == -1){
- perror("close");
- return EXIT_FAILURE;
- }
- printf("Przeslana wiadomosc: %s\n", buffer);
- // Wyslij
- memset(buffer, '\0', BUFFER_SIZE);
- printf("Podaj odpowiedz, ktora zostanie wyslana laczem nazwanym: ");
- fgets(buffer, BUFFER_SIZE, stdin);
- if(kill(pid, SIGUSR1) == -1){
- perror("kill");
- return EXIT_FAILURE;
- }
- if((fifofd = open(FIFO_DIR, O_WRONLY)) == -1){
- perror("open");
- return EXIT_FAILURE;
- }
- if(write(fifofd, buffer, BUFFER_SIZE) == -1){
- perror("write");
- return EXIT_FAILURE;
- }
- if(close(fifofd) == -1){
- perror("close");
- return EXIT_FAILURE;
- }
- if(unlink(FIFO_DIR) == -1){
- perror("unlink");
- return EXIT_FAILURE;
- }
- wait(NULL);
- }
- return EXIT_SUCCESS;
- }
Add Comment
Please, Sign In to add comment