读取和写入命名管道

时间:2018-03-20 03:37:18

标签: c named-pipes

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

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

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

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

  3. 我尝试使用fsync()进行刷新,但这也不起作用。

    customer.c

    <></>

    bank.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;
    }
    

    任何指针?

1 个答案:

答案 0 :(得分:0)

你需要为多个同时的recv制作多线程服务器。并且需要检查管道名称是否已存在。

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。 ./customer atm1 ./customer atm2

相关问题