阅读整个管道 - c

时间:2018-04-24 14:24:02

标签: c pipe dup feof

我对这段代码有些困难。 我需要从管道末端获取所有信息。 但是,我遇到了段错误。

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int main(void){

    int tube[2];

    if(pipe(tube) == -1){
        perror("Erreur");
        exit(1);
    }

    dup2(tube[1],1);

    printf("Few lines \n");
    printf("of an undefined size. \n");

    while (!feof(tube[0])) {
        char temp = fgetc(tube[0]);
        printf("chaine : %c\n", temp);
    }

    return 0;
}

如果您对如何处理此问题有所了解,谢谢^^

3 个答案:

答案 0 :(得分:2)

pipe函数返回的是 int 文件描述符对,而不是FILE个。这意味着您可以readwriteclose使用fgetcfeofwhile(!feof(file))

此外,stdout(几乎)总是wrong,因为在不成功的读取到达文件末尾后,标志设置为

并非全部。只有当写入端的所有描述符都关闭时,才会在管道的读取端获得EOF。因此,您必须关闭或刷新tube[1]以确保已将所有字符写入管道,如果尚未关闭stdout则关闭文件描述符1,并关闭仍为文件描述符的close(tube[1]); fclose(stdout); while (1) { char temp; if (read(tube[0], &temp, 1) < 1) break; fprintf(stderr, "chaine : %c\n", temp); } 写下管的末端。

所以你可以用:

替换你的while循环
feof

它修复了在fgetc上使用FILEprivate String getImagePath(int position) { String path = null; AssetManager assetManager = getAssets(); try { String[] imageNames = assetManager.list(foodType.getName(this)); path = foodType.getName(this) + "/" + imageNames[position]; } catch (IOException e) { e.printStackTrace(); } return path; } 引起的SEGFAULT,并确保在读取其内容之前正确关闭文件的写入结尾获得一个很好的文件结束条件。

答案 1 :(得分:1)

但是,我遇到了段错误。 ?表示您没有正确读取编译器警告。当您执行feof(tube[0])时,feof()预计会FILE*,但您已提供inttube[0]是inetger)类型。

  

/usr/include/stdio.h:828:12:注意:预期'struct FILE *'但是   参数的类型为'int'

所以首先要总是阅读编译器警告&amp;使用-Wall标志编译代码。

fgetc(tube[0]);不是从file descriptor读取数据的方法,使用read()系统调用从文件描述符中读取数据而不是fgetc()。如果您使用fgetc()打开文件,则可以使用fopen()

另外

dup2(tube[1],1); /* this is not expected one which you want*/

像这样使用

dup2(1,tube[1]);/*stdout get duplicated with tube[1] i.e whatever you
                        write on stdout will be written into write end of pipe*/

这是一个简单的例子。

char temp[100];
        int ret = 0;
        ret = read(tube[0],temp,sizeof(temp));/*reading from pipe*/
        if(ret == -1)   {
                perror("read");
                return 0;
        }
        else {
                temp[ret] = '\0';/*read returns no of items read, so put null
                                        at last otherwise you may get some junk data  */
                printf("%s",temp);
        }

阅读man 2 read&amp; man 2 dup2了解这些系统调用的工作原理..

答案 2 :(得分:0)

You're using a function that returns a single character (fgetc) then treating that value as a pointer to a string in your printf call. You're also storing that character as the address of the pointer to a character rather than as the actually character, so when printf goes to read your string it's reading some low memory that it doesn't own. fgetc returns the character itself, you you need a char variable, not a char*.

Try:

while (!feof(tube[0])) {
    char temp = fgetc(tube[0]);
    printf("chaine : %c\n", temp);
}