【问题标题】:Inconsistent reading of string from pipe从管道中读取字符串不一致
【发布时间】:2018-12-25 15:42:33
【问题描述】:

我从文件中读取一些数据,然后通过管道发送。当我从管道中读取数据时,有时里面会有多余的字符。额外的字符也不一致,但通常在末尾是一个额外的“R”。

我从文件中读取的数据是正确的,因为它总是应该的。只有在从管道中读取它之后,我才会遇到问题。

你能帮我找出错误吗?我已经盯着这个看很久了,我找不到它。

这是我的代码中给我带来麻烦的部分。

感谢您的帮助。

int main (int argc, char **argv) {

    int nClients;
    int file_name_HTML[2];

    create_pipes(file_name_HTML, server_access_request);
    init_free_pipes();

    nClients = getHTMLFilesIntoPipe(file_name_HTML);
    int clients[nClients];

    for(int i=0; i < nClients; i++)
    { 
        if((clients[i] = fork()) == 0) 
        { 
            clientFunction(file_name_HTML, server_access_request);
        } 
    }
    .....
}

int getHTMLFilesIntoPipe(int *file_name_HTML)
{
    int i, n = 0;
    char (*lines)[MAXCHAR] = NULL;
    FILE *fp;
    fp = fopen("./data/listado_html.txt", "r");

    if (!fp) {  /* valdiate file open for reading */
    err_exit("error: file open failed.\n");
    }

    if (!(lines = malloc (MAXLINES * sizeof *lines))) {
    err_exit("error: virtual memory exhausted 'lines'.\n");
    }

    while (n < MAXLINES && fgets (lines[n], MAXCHAR, fp)) /* read each line */
    { 
        char *p = lines[n];                 /* assign pointer  */
        for (; *p && *p != '\n'; p++) {}    /* find 1st '\n'   */
        if (*p != '\n') /* check line read */
        {                   
            int c;  
            while ((c = fgetc (fp)) != '\n' && c != EOF) {} /* discard remainder of line with getchar  */
        }
        *p = 0, n++;    /* nul-termiante   */
    }
    if (fp != stdin) fclose (fp);   /* close file if not stdin */

    for (int i = 0; i < n; i++)
    {
        write(file_name_HTML[WRITE], lines[i], strlen(lines[i]));
    }

    free(lines);

    return n;
}

void clientFunction(int *file_name_HTML, int *server_access_request)
{
    char fileName[MAXCHAR];

    close(file_name_HTML[WRITE]);
    //Read HTML file name
    read(file_name_HTML[READ], fileName, MAXCHAR - 1);
    printf("%s\n", fileName);

    .......
}

预期输出: abcd1.html

abcd2.html

abcd3.html

abcd4.html

abcd5.html

电流输出: abcd1.htmlR

abcd2.htmlR

abcd3.htmlR

abcd4.htmlR

abcd5.htmlR

【问题讨论】:

    标签: c pipe


    【解决方案1】:

    这是因为你的字符串不是 null(\0) 终止的。

    当您写入管道时,不包括 null(\0) 终止符。

    write(file_name_HTML[WRITE], lines[i], strlen(lines[i])+1);
                                                            ^--- +1 to include null character.
    

    strlen 返回不包括空终止符的长度。

    【讨论】:

    • 我不知道我是怎么错过的......谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多