Shell脚本终止程序,但导致无法写入输出文件

Shell script to terminate program but causes output file to not be written

本文关键字:输出 文件 终止程序 脚本 Shell      更新时间:2023-10-16

我想在后台运行一个程序,收集一些性能数据,然后在前台运行一个应用程序。当前台应用程序完成时,它会检测到这一点,并在后台关闭应用程序。问题是,当后台应用程序在没有首先关闭文件的情况下关闭时,我假设文件的输出仍然为空。是否有一种方法可以不断写入输出文件,以便在后台应用程序意外关闭时保留输出?

这是我的shell脚本:

./background_application -o=output.csv &
background_pid=$!
./foreground_application
ps -a | grep foreground_application
if pgrep foreground_application > /dev/null
then
     result=1
else
     result=0
fi
while [ result -ne 0 ]
do
     if pgrep RPx > /dev/null
     then
          result=1
     else
          result=0
     fi
     sleep 10
done
kill $background_pid
echo "Finished"

我可以访问用C++编写的后台应用程序的源代码,这是一个基本循环,每次循环迭代都会运行fflush(outputfile)。

这会更短:

./background_application -o=output.csv &
background_pid=$!
./foreground_application
cp output.csv output_last_look.csv
kill $background_pid
echo "Finished"