首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Fflush不写入缓冲文本

Fflush不写入缓冲文本
EN

Stack Overflow用户
提问于 2016-12-14 04:07:57
回答 1查看 63关注 0票数 0

我正在尝试使用以下代码将2D表格打印到我的终端:

代码语言:javascript
复制
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <termios.h>
#include <sys/wait.h>

char getch()
{
    char ch;
    struct termios old, new;
    tcgetattr(0, &old); // grab old terminal i/o settings
    new = old; // new settings = old settings
    new.c_lflag &= ~ICANON; // disable buffered i/o
    new.c_lflag &= ~ECHO; //set echo mode
    tcsetattr(0, TCSANOW, &new); // use these new terminal i/o settings now
    ch = getchar();
    tcsetattr(0, TCSANOW, &old); //restore old settings
    return ch;
}

void readPBM(char *output)
{
    char tmp[1024];

    int fd[2] = {0,0};
    int pid;

    //Open the pipe for inter-process communication
    pipe(&fd[0]);

    //Fork and test if we are child or parent process
    pid = fork();
    if(pid) //Parent process
    {
        wait(NULL); //Wait for child's end
        close(fd[1]);//Close pipe's write stream
        close(0);//Close stdin
        dup(fd[0]);//Duplicate stdout
        close(fd[0]);//Close old stdout

        strcpy(output, "");// Init output at 0
        while(fgets(tmp, 1024, stdin) != NULL) //Put remaining entry in output
        {
            strcat(output, tmp);
        }
    }
    else if(pid == 0) //Child process
    {
        close(fd[0]);//Close pipe's read stream
        close(1);//Close stdout
        dup(fd[1]);//Duplicate stdin
        close(fd[1]);//Close old stdin

        printf("A random string ...\n");
    }
    else //Print error if fork failed
    {
        printf("Error creating a new process");
        exit(EXIT_FAILURE);
    }
}

int main(int argc, char *argv[])
{
    int i, j;

    char *str = NULL;
    char c;

    str = malloc(512 * sizeof(char*));

    readPBM(str);

    printf("%s", str);
    fflush(stdout);
    c = getch();
}

我有一台UNIX implementation of getch()

我的问题是我的程序正在等待一个输入来打印表。我尝试fflush(stdout)和禁用终端缓冲与ICANON,但它仍然不起作用。

PS:它在getchar,scanf,...

编辑:所以我举了一个最小的例子;它似乎与管道有关。

EN

回答 1

Stack Overflow用户

发布于 2018-10-02 20:18:18

我的问题是我的程序正在等待一个输入来打印表。

这是因为您在子进程完成工作时忘记了终止它,所以在将A random string ...打印到管道之后,它会继续执行,从readPBM()返回,并最终在main()结束时执行c = getch()。补救方法是在if(pid == 0) //Child process块的末尾调用exit(0)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41129695

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档