繁体   English   中英

将变量从C程序传递到Shell脚本作为参数

[英]Passing variable from c program to shell script as argument

我正在从“ c”程序调用shell脚本,并且在c中有一些变量希望作为参数传递给shell脚本。 我尝试使用system()调用Shell脚本,但我作为参数传递的变量被视为字符串而不是变量。

Shell脚本(a.sh):

# iterates over argument list and prints
for (( i=1;$i<=$#;i=$i+1 ))
do
     echo ${!i}  
done

C代码:

#include <stdio.h>

int main() { 
  char arr[] = {'a', 'b', 'c', 'd', 'e'}; 
  char cmd[1024] = {0}; // change this for more length
  char *base = "bash a.sh "; // note trailine ' ' (space) 
  sprintf(cmd, "%s", base);
  int i;
  for (i=0;i<sizeof(arr)/sizeof(arr[0]);i++) {
    sprintf(cmd, "%s%c ", cmd, arr[i]); 
  }
  system(cmd);
}

您将必须构造一个包含完整命令行的字符串,以便system执行。 最简单的方法可能是使用sprintf

char buf[100];
sprintf(buf, "progname %d %s", intarg, strarg);
system(buf);

这是入门的快速方法。

但是,还有forkexec的双重功能(至少对于unix系统而言)。 如果您的参数已经是单独的字符串,那么这比真正复杂的格式规范要容易得多; 更不用说为复杂的格式规格计算正确的缓冲区大小了!

if (fork() == 0) {
    execl(progname, strarg1, strarg2, (char *)NULL);
}
int status;
wait(&status);
if (status != 0) {
    printf("error executing program %s. return code: %d\n", progname, status);
}

这个下面的程序对我有用

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char const *argv[])
{

char buf[1000]; //change this length according to your arguments length

  int i;
  for (i=0;i<argc;i++) {
    if(i==0)
    {
    sprintf(buf, "%s", "sh shell-scriptname.sh");
    sprintf(&buf[strlen(buf)]," ");
    }
    else
    {
        sprintf(&buf[strlen(buf)],argv[i]);

        sprintf(&buf[strlen(buf)]," ");
    }


  }

  //printf("command is %s",buf);

    system(buf);
}

我的Shell脚本有类似的参数

sh shell-scriptname.sh -ax -by -cz -d blah / blah / blah

我使用以下代码编译了C程序

gcc c-programname.c -o实用程序名称

执行

./实用程序名称-ax -by -cz -d blah / blah / blah

为我工作

这不会打印子进程的返回状态。

返回状态是一个16位字。 对于正常终止:字节0的值为零,返回码在字节1中。由于未捕获的信号而终止:字节0的信号编号,字节1为零。

要打印退货状态,您将需要执行以下操作:

 while ((child_pid =wait(&save_status ))  != -1 )  {
  status = save_status >> 8;
  printf("Child pid: %d with status %d\n",child_pid,status);

暂无
暂无

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

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