小编Era*_*ran的帖子

禁用分叉进程的stdout缓冲

我在C/C++中编写了一个代码,用于处理子进程,将stdin/stdout复制到管道末端并调用execvp.

一切正常(即父进程捕获stdin/err/out的输出)

问题是子缓冲区是缓冲的.

所以如果子代码看起来像这样:

printf("Enter any key and hit ENTER:\n");
fgets(line);
printf("read: %s\n", line);
exit(0);
Run Code Online (Sandbox Code Playgroud)

在父进程中,我没有看到"输入任何键:"行 - 只有在程序调用exit(自动刷新stdout缓冲区)或显式调用'flush(stdout)'后才会"刷新"它添加

我做了一些研究并尝试添加一个调用来禁用stdout缓冲,方法是添加一个调用:

setvbuf(stdout,NULL,_IONBF,0); 就在父进程中调用execvp(...)之前

所以相关代码现在看起来像这样:

int rc = fork();
if ( rc == 0 ) {
    // Child process
    if(workingDirectory.IsEmpty() == false) {
        wxSetWorkingDirectory( workingDirectory );
    }
    int stdin_file  = fileno( stdin  );
    int stdout_file = fileno( stdout );
    int stderr_file = fileno( stderr );

    // Replace stdin/out with our pipe ends
    dup2 ( stdin_pipe_read,  stdin_file );
    close( stdin_pipe_write );

    dup2 ( stdout_pipe_write, …
Run Code Online (Sandbox Code Playgroud)

c c++ posix

8
推荐指数
1
解决办法
4535
查看次数

标签 统计

c ×1

c++ ×1

posix ×1