如何从 运行 和 bash 脚本的 C 程序中获取变量的值?

How can I get the value of a variable from a C program I've run with a bash script?

我 运行 我的程序在一个 for 循环中,传递给它 num_threads 的不同值。

for (( j=1; j<9; j++ ))
    do
        mpirun -n $j ./my_program
    done

我知道 bash 会将 return 值存储在 $?自动地。但是,我想要做的是在向并行程序传递 num_threads=1 的参数时获取并行程序的运行时间,这样我就可以使用这个值来找到当 运行 这个程序时 num_threads>1.为此,我需要 return 双倍,我曾尝试 return 来自 main() 的双倍:

double main(int argc, char** argv) {
double run_time;
...

return run_time;

}

但似乎 main() 只能 return 一个整数,我从我的 bash 脚本中得到一个 0。

time=$?
echo $time

output:
0

从您的程序中输出值。

int main(int argc, char** argv) {
    double run_time;
    ...
    
    fprintf(stderr, "%f\n", run_time);
}

然后:

for (( j=1; j<9; j++ )); do
    echo -n "$j " >> speed.txt
    mpirun -n $j ./my_program 2>>speed.txt
    # or you want to see it
    # mpirun -n $j ./my_program 2> >(tee -a speed.txt >&2)
done
sort -k2g speed.txt   # -g is from GNU sort

通常,double main(int, char**) 形式无效 - main 必须仅具有特定形式,请参阅 https://en.cppreference.com/w/cpp/language/main_function