简体   繁体   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. 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. The problem is when i run this C program through bash to get distance, i am not able to redirect its output to any file or variable.问题是当我通过 bash 运行此 C 程序以获取距离时,我无法将其 output 重定向到任何文件或变量。 i tried this: output=$(./run) but it is not working.我试过这个: output=$(./run) 但它不工作。 to run C code inside bash i am using the following code:在 bash 中运行 C 代码,我使用以下代码:

#!/bin/bash

echo 'clear'

echo enter file name

read FILE

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

when i do not redirect it shows value:当我不重定向时,它显示值:


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

./a.out

[gps values ][1] [gps 值][1]

Can any body help in this?任何机构都可以在这方面提供帮助吗?

You don't include the requested debug log, but from your screenshot it looks like your program never exits.您没有包含请求的调试日志,但从您的屏幕截图看来,您的程序永远不会退出。 It just stays around and writes values forever.它只是一直存在并永远写入值。 Therefore, the capture never reaches the end, so your echo statement never executes.因此,捕获永远不会结束,因此您的echo语句永远不会执行。

You should modify your program or invocation so that it will at some point exit.您应该修改您的程序或调用,以便它在某个时候退出。

If you can't modify the program, you can capture eg only the first ten lines using one of:如果您无法修改程序,则可以使用以下之一仅捕获前十行:

# 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) ) 

Thank you every one for the comments It is working now谢谢大家的意见 现在正在工作

#!/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

by using the above code通过使用上面的代码

Use -o flag in gcc to create the binary first.在 gcc 中使用 -o 标志首先创建二进制文件。

I'll give you an example using "Hello World" code:我会给你一个使用“Hello World”代码的例子:

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

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

The bash script: bash 脚本:

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

Then run:然后运行:

~]# bash hw.sh
Hello World

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

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