Prova Pratica Es.2 12-02-2009

From Sistemi Operativi
Jump to navigation Jump to search

Soluzione di Dado e Pierg

Scrivere un programma in linguaggio C che crei due named pipe (passate per argomento), le apra in lettura e
e copi in standard output i dati via via disponibili da ogni pipe.
Test di funzionamento: aprire tre finestre di emulazione terminale. Nella prima lanciare: mergepipe p1 p2, nella seconda:
cat >p1, nella terza cat>p2.
Tutto cio' che scriverete o nella seconda o nella terza finestra deve comparire nella prima.
#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MAX 2048

int main (int argc, char *argv[]) {
    if (argc < 3) {
        perror("Argomenti sbagliati");
    }
    else {
        struct pollfd pino [2];
        nfds_t n = 2;
        char buf[MAX];
        
        mkfifo(argv[1], 0666);
        mkfifo(argv[2], 0666);
        pino[0].fd = open(argv[1], O_RDONLY | O_NONBLOCK);
        pino[1].fd = open(argv[2], O_RDONLY | O_NONBLOCK);
        pino[0].events = POLLIN;
        pino[1].events = POLLIN;
        
        while(1) {
            int ret = poll(pino, n, 100);
            if (ret == 1) {
                if (pino[0].revents == POLLIN) {
                    ssize_t x = read(pino[0].fd, buf, MAX);
                    buf[x+1] = '\0';
                    printf("%s", buf);
                    pino[0].revents = 0;
                }
                else {
                    ssize_t x = read(pino[1].fd, buf, MAX);
                    buf[x+1] = '\0';
                    printf("%s", buf);
                    pino[1].revents = 0;
                }
            }
            else if (ret == 2) {
                ssize_t x = read(pino[0].fd, buf, MAX);
                buf[x+1] = '\0';
                printf("%s", buf);
                pino[0].revents = 0;
                x = read(pino[1].fd, buf, MAX);
                buf[x+1] = '\0';
                printf("%s", buf);
                pino[1].revents = 0;
            }
        }
    }
}