繁体   English   中英

C 程序在 bash 脚本中

[英]C program with in bash script

I am trying to run C program inside bash, my C program is using the gps device and calculating the distance based on latitude and longitude values. 问题是当我通过 bash 运行此 C 程序以获取距离时,我无法将其 output 重定向到任何文件或变量。 我试过这个: output=$(./run) 但它不工作。 在 bash 中运行 C 代码,我使用以下代码:

#!/bin/bash

echo 'clear'

echo enter file name

read FILE

gcc -o a.out $FILE -lm 
output=$(./a.out) 
echo $output

当我不重定向时,它显示值:


#!/bin/bash
echo `clear`
echo enter file name
read FILE
gcc -o a.out $FILE -lm 

./a.out

[gps 值][1]

任何机构都可以在这方面提供帮助吗?

您没有包含请求的调试日志,但从您的屏幕截图看来,您的程序永远不会退出。 它只是一直存在并永远写入值。 因此,捕获永远不会结束,因此您的echo语句永远不会执行。

您应该修改您的程序或调用,以便它在某个时候退出。

如果您无法修改程序,则可以使用以下之一仅捕获前十行:

# More canonical way
output=$(./a.out | head -n 10)

# More resilient way, if the program is especially poorly written
output=$( head -n 10 <(./a.out) ) 

谢谢大家的意见 现在正在工作

#!/bin/bash

echo `clear`
echo enter file name
read FILE
gcc -o a.out $FILE -lm 

stdbuf -oL ./a.out |
  while IFS= read -r line
  do
    echo "Data: $line"
  done

通过使用上面的代码

在 gcc 中使用 -o 标志首先创建二进制文件。

我会给你一个使用“Hello World”代码的例子:

~]# cat hw.c
#include <stdio.h>

int main(){
        printf("Hello World");
        return 0;
}

bash 脚本:

~]# cat hw.sh
gcc -o hw hw.c
./hw

然后运行:

~]# bash hw.sh
Hello World

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM