簡體   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