为什么linux管道和标准输出不能一起工作
Why linux pipes and stdout from exec not working together?
我用linux管道写代码,不明白为什么只有printfs(1)或只有exec(2)进入父进程的输入。如果我注释exec,那么打印工作正常。如果取消注释,只显示"ls"输出
int main(void)
{
int fd[2], pid;
if (pipe(fd) != 0) return 1;
if ((pid = fork()) == -1) return 1;
if (pid == 0) // child
{
close( STDOUT_FILENO );
dup2( fd[1], STDOUT_FILENO );
close( fd[0] );
close( fd[1] ); // */
printf( "hellon" ); // (1)
printf( "hello2n" );
// execl( "/bin/ls", "ls", NULL ); // (2)
printf( "exec not executedn");
}
else
{
close( STDIN_FILENO );
dup2( fd[0], STDIN_FILENO );
close( fd[0] );
close( fd[1] );
char buf[100];
while( gets( buf ) != NULL )
printf( "message: %sn", buf );
}
}
exec注释时的输出:
消息:你好
消息:hello2
消息:exec not executed
当exec没有注释时:
信息:filt1
信息:filt1.d
…其他文件
信息:makefile
信息:objects.mk
默认情况下,stdio完全缓冲输出到流,除非它写入终端(stderr
除外,它是未缓冲的)。因此,管道的输出正在被缓冲。
当你调用execl()
时,当前进程的内存被丢弃,并被你正在加载的程序所取代。这将导致工作室输出缓冲区被丢弃,因此它们永远不会被写入管道。
简单的解决方法是先呼叫fflush(stdout);
,再呼叫execl()
。
相关文章:
- 为什么我不能将 rand() 与数组的大小一起使用?
- 不能将复制初始化与隐式转换的多个步骤一起使用
- Python 3.8 不能与 Pybind11 一起导入 [Windows]
- Turbo C++ cin() 不能与 gets() 一起使用
- 不能将重载比较运算符与 Catch 测试一起使用
- 不能将C++的"std::filesystem"库与介子构建一起使用
- C++程序在将 int 与 cin 一起使用时有效,但不能使用字符串
- std::remove() 按预期处理文字,但不能与取消引用的迭代器一起工作
- 为什么我不能将运算符+与reverse_iterator一起使用?
- 为什么引用和指针不能一起使用?
- C++:printf 和 wprintf 不能一起工作 (Linux)
- Apple Mach-O Linker (ld) 错误.ld: -r 和 -dead-strip 不能一起使用
- typeinfo name() 和 endl 在 Windows 和 mingw 中不能一起工作
- boost和Curl不能一起工作
- Q_ENUMS和using声明不能一起工作
- 为什么linux管道和标准输出不能一起工作
- c++ /OpenGL: vao单独工作,但不能一起工作
- 类型定义和函数声明不能一起工作
- pcap_stats和pcap_dump_open不能一起工作
- OSX 10.8.5 上的 Android 构建错误:cp:-R 和 -r 选项不能一起指定