注册 登录
编程论坛 C语言论坛

linux 中怎么清空fifo管道的数据?

fuxingC80 发布于 2020-07-27 15:37, 2468 次点击
想在两个程序间通信,但管道的数据会一直结尾追加,不能清空从头开始发数据,求大佬!

读端:
int main(){
    char *filename = "/home/hi/testprog/my_fifo";
    int fd;
    char buf_r[100];
    int nread;
    int i = 0;
    fd = open(filename,O_RDONLY);
    if(fd == -1){
        printf("open file fail!!\n");
        return 0;
    }
    printf("hello , start to test reading!!!\n");
    while(1)
    {
        memset(buf_r,0x00,sizeof(buf_r));
        if((nread = read(fd, buf_r, 100)) == -1)
        {

        printf("从FIFO读取的数据为:%s\n", buf_r);
        for(i;i<20;i++){
            printf("%d",buf_r[i]);
        }        
        i = 0;
        fflush(stdout);
        sleep(1);
    }   
    return 0;
}

写端:
int main(){
    char *c;
    char *str;
    str = malloc(100*sizeof(char*));
    c = malloc(100*sizeof(char*));
    char *filename = "/home/hi/testprog/my_fifo";
    int res = mkfifo(filename,0777);   
    int fd;
    if(res != 0){
        fprintf(stderr,"fifo creat file fail!!\n");
        exit(EXIT_FAILURE);
    }
    fd = open(filename,O_WRONLY);
    if(fd == -1){
        printf("open file fail!!\n");
        return 0;
    }
    printf("hello , start test to writing!!!\n");
    while(1)
    {   
        fflush(stdout);
        while((*c = getchar()) != '\n'){
            strcat(str,c);
        }
        write(fd,str,100);
        printf("end of write!\n");
        sleep(1);
    }
    return 0;
}
0 回复
1