C 带浮子的管道

C 带浮子的管道,c,pipe,C,Pipe,管道会不断截断数字的整个部分,但第一部分除外 #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> void errexit(char *errMsg) { printf("

管道会不断截断数字的整个部分,但第一部分除外

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

void errexit(char *errMsg)
{
    printf("\n About to exit: %s", errMsg) ;
    fflush(stdout) ;
    exit(1) ;
}

int main()
{
    int ret ;
    pid_t pid ;
    double adder ;
    double value ;
    char fifoName[] = "/tmp/testfifo" ;
    char errMsg[1000] ;
    FILE *cfp ;
    FILE *pfp ;

    ret = mknod(fifoName, S_IFIFO | 0600, 0) ;      // 0600 gives read, write permissions to user and none to group and world

    if(ret < 0)
    {
        sprintf(errMsg,"Unable to create fifo: %s",fifoName) ;
        errexit(errMsg) ;
    } 

    pid = fork() ;

    if(pid == 0)
    {
        // child -- open the named pipe and write an integer to it 
        cfp = fopen(fifoName,"w") ;
        if(cfp == NULL) 
            errexit("Unable to open fifo for writing") ;
        adder = 1.1 ;
        value = 1.1 ;
        while (value < 10)
        {
            ret=fprintf(cfp,"%lf",value) ;
            printf("Child sending %lf\n", value) ;
            //fflush(cfp) ;
            value = value + adder ;
        }
        exit(0) ;
    } 
    else
    {
        printf("Spawned child %d\n", pid) ;

        // parent - open the named pipe and read an integer from it
        pfp = fopen(fifoName,"r") ;
        if(pfp == NULL) 
            errexit("Unable to open fifo for reading") ;

        //while (fscanf(pfp, "%e", &value) > 0)
        while (fscanf(pfp, "%lf", &value) > 0)
        {
            printf("This is the parent. Received value %lf from child on fifo \n", value) ;

            sleep(1) ;
            value = 0 ;
        }
        fclose(pfp) ;
        printf("Bye\n") ;
        unlink(fifoName); // Delete the created fifo
        exit(0);
    }
}

它将第一个部分取对1.1,但之后它将整个部分去掉,但将小数部分取对。Fedora25上的GCC编译器。我已经能够通过管道获得字符串和整数,但是没有太多的运气通过管道获得一个double。

因为生产者正在编写如下值:

fprintf(cfp,"%lf",value) ;
如果没有空格,则值将显示为一个连续流:

1.1000002.2000003.3000004.400000

我猜消费者正在阅读,例如,1.1000002,然后因为下一个错误而停止。不是该值的一部分,例如,将2000003留给下一个fscanf


如果添加换行符或空格来分隔这些值,那么一切都会正常进行。

谢谢,我已经被困了好几个小时了。把一条线换成了汉克斯,卡了几个小时。将一行更改为ret=fprintfcfp,%lf,value;工作正常now@brianl>尽管是完全可选的,但在流中使用基于文本的消息时,一个常见的约定是使用“\n”最常见的大小写,或者在文本可能包含换行符作为分隔符时使用“\0”。
fprintf(cfp,"%lf",value) ;