读写命名管道

Reading and Writing to a Named Pipe

我正在使用两个程序。 customer.c 程序将 int 写入命名管道,bank.c 读取管道并打印 int。客户将选择两个命名管道之一,"atm1" 和 "atm2"。

最终我想 运行 两个 customer.c 程序,每个管道同时一个,但我在写入和读取命名管道时遇到一些问题。

  1. 如果我只是 运行 bank.c 和一个 customer.c 我没有得到任何输出。

  2. 如果我 运行 bank.c 和两个 customer.c 输出并不总是打印或者打印时出现故障。

我尝试使用 fsync() 进行刷新,但也没有用。

customer.c

int main(int argc, char *argv[]){
    int fd, num =0;
    if((fd = open(argv[1], O_WRONLY)) == -1){
        ...
    }
    while(1){
        printf("Enter a integer:\n");
        scanf("%d", &num);
        if(num < 0){
            break;
        }
        if(write(fd, &num, sizeof(num)) <= 0){...}
        fsync(fd);
    }
    close(fd);
    return 0;
}

bank.c

int main(){
    int fd, sd, num=0, sret, fret, maxfd;
    //fd_set readfds;
    //struct timeval timeout;

    if(mkfifo("atm1", 0666) == -1){...}
    if(mkfifo("atm2", 0666) == -1){...}
    if((fd = open("atm1", O_RDONLY)) == -1){...}
    if((sd = open("atm2", O_RDONLY)) == -1){...}

    while(1){
        if((sret = read(sd, &num, sizeof(num))) > 0){
             printf("%d\n", num);
        }
        if((fret = read(fd, &num, sizeof(num))) > 0){
             printf("%d\n", num);
        }
        if(sret <= 0 && fret <= 0){
             break;
        }
    }
    close(fd);
    close(sd);
    return 0;
}

有指针吗?

您需要为多个同时接收建立 multi-threads 服务器。并要求检查管道名称是否已经存在。

blank.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <pthread.h>

void *client(void *data) 
{
    char *pname = (char*) data ;
    int sd =0 ;
    int num ;
    int sret=0 ;

    if((sd = open(pname, O_RDONLY)) == -1) {
        printf("open failed:%s\n", pname) ;
        return NULL ;
    }
    printf("client[%d] start\n", sd) ;
    while(1){
        num=0 ;
        if((sret = read(sd, &num, sizeof(num))) > 0){
             printf("[%d] recv:%d\n", sd, num);
        }
        if(sret <= 0) {
             break;
        }
    }
    close(sd);
    printf("client[%d] end\n", sd) ;
    return NULL;
}

int main(){
    int status ;
    pthread_t t1, t2 ;

    if(mkfifo("atm1", 0666) == -1) {
    printf("mkfifio failed : %d\n", errno) ;
    if (errno==EEXIST ) {
        printf("already exist. ignore\n") ;
    }
    else
        return -1;
    }
    if(mkfifo("atm2", 0666) == -1) {
    printf("mkfifio failed2 : %d\n", errno) ;
    if (errno==EEXIST ) {
        printf("already exist. ignore\n") ;
    }
    else
        return -1;
    }

    pthread_create(&t1, NULL, client, (void*)"atm1") ;
    pthread_create(&t2, NULL, client, (void*)"atm2") ;

    pthread_join(t1, (void**)&status) ;
    pthread_join(t2, (void**)&status) ;

    return 0;
}

您可以同时访问atm1和atm2。 ./客户atm1 ./客户atm2