连接Fifos(客户端/服务器程序)

时间:2015-03-27 18:09:01

标签: c linux

我正在尝试创建一个简单的客户端/服务器程序,并学习如何与Fifos一起工作。

程序会创建一个fifo(FifoServer__)并在打开时阻止,这是预期的。但是,当我从另一端打开它时,它也会阻塞!我看了几个例子并试了很多东西,但我无法弄明白。

任何提示都将受到高度赞赏。

//header.h


# include <stdlib.h>
# include <fcntl.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <unistd.h>
# include <stdio.h>
# include <errno.h>
# include <signal.h>
# include <stdarg.h>

#define fifoServer "FifoServer__"

server.c:

# include "header.h"

int main(int argc, char ** argv)
{
    int serverfd;
    int client_pid;

    if (mkfifo( fifoServer, S_IRUSR | S_IWUSR | S_IWGRP) == -1) {
        perror("could not mkfifo");
        exit(EXIT_FAILURE);
    }        

    serverfd = open(fifoServer, O_RDONLY); //It blocks right here.
    if (serverfd == -1) {
        perror("failed to open fifo");
        exit(EXIT_FAILURE);
    }        

    //Signal handeling
    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
        perror("Could not Ignore SIGPIPE. Error: %d\n");
        exit(EXIT_FAILURE);
    }

    //listening for connections requests (client's pid)
    while (1) { 
        if (read(serverfd, &client_pid, sizeof(client_pid)))
                printf("Client's pid: %d", client_pid);
        break;
    }

    // Unlinking and cleaning Fifoserver__
    close(serverfd);
    unlink(fifoServer); 
    remove(fifoServer); 

return 0;
}

客户端:

# include "header.h"

int main(int argc, char ** argv)
{
    int serverfd;
    int client_pid;

    client_pid = getpid();

    serverfd = open(fifoServer, O_WRONLY);   //It blocks right here
    if (serverfd == -1) {
         perror("failed to open fifo");
         exit(EXIT_FAILURE);
    }

    if (write(serverfd, &client_pid, sizeof(client_pid)) == -1) {
        perror("Could not open Client Fifo Writer. Error: %d\n");
        exit(EXIT_FAILURE);
    }

    printf("Success !\n");
    close(serverfd);
    unlink(fifoServer);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

查看有关非阻止I / O http://cr.yp.to/unix/nonblock.html

的这篇文章