gpt4 book ai didi

ruby 脚本 : parent output missing after exec

转载 作者:数据小太阳 更新时间:2023-10-29 08:02:30 26 4
gpt4 key购买 nike

我有一个 ruby​​ 脚本,它会写入一些输出,然后 exec 执行一个命令。该命令想要继承父级的文件描述符,因为它将从 stdin 中读取,以某种方式对其进行转换,然后将输出写入 stdout

举个例子

#!/usr/bin/env ruby
puts 'hello from parent'
exec 'tr', '[:lower:]', '[:upper:]'

如果我们直接在 shell 中运行它,我们会看到两行输出

$ echo 'hello, world!' | ./example.rb
hello from parent
HELLO, WORLD!

但是,如果进程的 stdout 被重定向,我们将丢失来自父进程的输出。

$ echo 'hello, world!' | ./example.rb | cat
HELLO, WORLD!

这是为什么?第一种情况和第二种情况有什么区别?

此外,如果我们将 ruby​​ 脚本中的 exec 更改为 system,那么这两行都会打印到终端。是什么导致了这种行为差异?


只是为了比较,一个大致相同的 bash 脚本似乎没有表现出相同的行为:

#!/bin/bash
echo 'hello from parent'
exec 'tr' '[:lower:]' '[:upper:]'

我们从父级和子级获得输出。

$ echo 'hello, world!' | ./example.sh | cat
hello from parent
HELLO, WORLD!

最佳答案

听起来 Ruby 在 exec 另一个程序之前不会刷新标准输出。您可以显式刷新标准输出。

[STEP 105] # cat example.rb
#!/usr/bin/env ruby
puts 'hello from parent'
$stdout.flush
exec 'tr', '[:lower:]', '[:upper:]'
[STEP 106] # echo 'hello, world!' | ./example.rb | cat
hello from parent
HELLO, WORLD!
[STEP 107] #

关于 ruby 脚本 : parent output missing after exec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48734971/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com