bash - 将 ffmpeg (stderr) 输出重定向到 WHILE READ & 检索进程 ID

标签 bash ffmpeg pipe io-redirection

我可以重定向 ffmpeg 的 stderrwhile read :

ffmpeg -stream_loop -1 -re -i colors.mp4 -vf freezedetect=n=-20dB:d=2 \
-f null - 2>&1 | while read line; \
do if [[ $line =~ "freeze_start" ]] ;\
then echo [`date`] >> freeze_start.log ;\
echo [`date`] ;\
fi ; done;\
echo $! > pid.log
结果:
  • 每次 ffmpeg 输出 freeze_startstderr , 当前日期显示在 shell 中并写入 freeze_start.log
  • 问题:一些进程 ID 被写入 pid.log .不是 ffmpeg 的进程 ID过程。

  • 如何检索 ffmpeg的进程 ID 为 &同时仍然可以使用 while read在管道上 stderr ?
    我在哪里可以放置 &为了使这项工作?
    当我添加 &...-f null -& 2>&1 | while...结果是:
  • ffmpeg 的正确进程 ID进程写入pid.log .
  • 问题: freeze_start.log未创建。我猜 &干扰 IO 重定向。
    ffmpeg -stream_loop -1 -re -i colors.mp4 -vf freezedetect=n=-20dB:d=2 \
    -f null -& 2>&1 | while read line; \
    do if [[ $line =~ "freeze_start" ]] ;\
    then echo [`date`] >> freeze_start.log ;\
    echo [`date`] ;\
    fi ; done;\
    echo $! > pid.log
    

  • 您可以轻松创建输入 colors.mp4 :
    ffmpeg -f lavfi -i color=c=red -frames:v 1 color001.jpg && \
    ffmpeg -f lavfi -i color=c=green -frames:v 1 color002.jpg && \
    ffmpeg -f lavfi -i color=c=blue -frames:v 1 color003.jpg && \
    ffmpeg -framerate 1/5 -i color%03d.jpg -c:v libx264 -r 30 -pix_fmt yuv420p colors.mp4
    

    最佳答案

    你可以把 &在整个管道的末尾并使用 jobs -p 检索管道中第一个命令的 PID (此处不使用 $!,因为它会为您提供管道中最后一个命令的 PID):

    #!/bin/bash
    
    ffmpeg -stream_loop -1 -re -i colors.mp4 -vf freezedetect=n=-20dB:d=2 -f null - 2>&1 |
    while IFS='' read -r line
    do
        [[ $line =~ "freeze_start" ]] && echo "[$(date)]"
    done |
    tee -a freeze_start.log &
    
    # showing what is what:
    ps -f $(jobs -p) $!
    
    # this one is ffmpeg's PID
    jobs -p > pid.log
    
    # wait for completion
    wait
    

    关于bash - 将 ffmpeg (stderr) 输出重定向到 WHILE READ & 检索进程 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70918755/

    相关文章:

    python - 在 2.7.3 OSX Lion 中使用 panda3D

    linux - 如何在linux脚本中提取字符串中的数字和特殊字符

    ruby-on-rails - 将 GridFS 文件对象转换为文件对象以通过 carriewave 上传,然后在 Rails 中使用 ffmpeg 进行处理

    ffmpeg - 如何让icecast从ffmpeg中继mp3流的元数据?

    bash - 使用 sed 从多行中提取引用值

    linux - Bash:如果工作完成就 catch

    FFmpeg 时间戳

    c - fork 后的 Unix dup 管道

    unix - 为什么 "yes | head"不挂?

    c - fork一个进程,并使用管道将数据从文件逐行传输到子进程