c - 调用shell脚本后返回主C程序

标签 c linux bash shell

我有一个在 Raspberry-Pi 上运行的 C 程序,它不断地从 AVR 读取串行信息。我想使用简单的 shell 脚本编写接收到的命令的历史记录:

#!/bin/bash

echo "Command $2 received from address $1" 

date_time=$(date)                       #read current date from terminal
echo " $date_time Address: $1 Cmd: $2" >> file.txt      #echo address & command to file, redirect stdio

exit 0

当使用正确的参数在终端内调用时,该脚本可以完美运行,但是,我想在每次从串行线路读取命令时执行它。 C程序当前读取命令和地址并将其打印到标准io,所以我想做的是在此之后调用脚本,将数据写入文件。

当像这样在我的代码中调用脚本时:

    char* args[3];
char* program="ioExport.sh";
    args[1]=addr;
    args[2]=cmd;
    args[3]=NULL;
    execv(program,args);

退出主程序。调用脚本后如何返回主程序?或者当脚本作为后台进程运行时有没有办法做到这一点?我知道使用标准 C 文件 i/o 会更简单,但如果可以使用 shell,我想这样做:)

问候, 哈科

最佳答案

exec 系列函数用新进程替换该进程。它们仅在出现错误时返回。

您似乎想要的是 system函数,它为您创建一个 shell 进程,然后执行参数中的命令。

顺便说一句,无论如何,您都错误地设置了参数数组,请记住数组索引以开头。此外,argument 数组中的第一个条目应该是程序名称,这意味着您需要将 argument[0] 设置为 program,并且当然将数组大小更改为 4。


但是,正如 trojanfoe 所指出的,您根本不需要调用 shell 脚本,除非在收到消息时需要运行一些其他特殊命令。如果您只想将一些日志信息打印到一个文件,您可以非常轻松地从程序内部完成此操作:

/* First get the date and time string */
time_t now = time(NULL);
char *timestring = ctime(&now);

/* It contains a trailing newline, remove that by */
/* overwriting the newline with the string terminator */
timestring[strlen(timestring) - 1] = '\0';

/* Open the file for appending (i.e. writing at the end) */
FILE *file = fopen("file.txt", "a");

/* And write your message to your file */
fprintf(file, "%s Address: %s Cmd: %s\n", timestring, addr, cmd);

/* Close the file */
fclose(file);

将其放在一个单独的函数中,您可以在需要时调用该函数。请注意,如果您想向文件写入更多内容,则可以在程序开始时打开它,直到退出程序才将其关闭。

关于c - 调用shell脚本后返回主C程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18592196/

相关文章:

c++ - 逗号作为变量初始化中的分隔符(不是作为运算符)

c - 如何在列表中的句柄上使用 free?-> C -> Windows API

c - printf double 不带尾随零

bash - 确定 `set -e` 标志是否在 bash 中处于事件状态

c - 改变可变参数

linux - Centos 6.5 super 用户root丢失

linux - 如何将 stdout 写入 git bash 上的任何文件?

linux - 使此代码从文件中读取

perl - 我如何将 "look behind"的 bash 命令行参数扩展?

linux - 如何将数组值添加到文本文件中特定行的开头