将变量作为参数从c程序传递到shell脚本

将变量作为参数从c程序传递到shell脚本,c,shell,variables,arguments,C,Shell,Variables,Arguments,我正在从“c”程序调用一个shell脚本,并且在c中有一些变量,我希望将这些变量作为参数传递给shell脚本。我尝试使用系统调用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() {

我正在从“c”程序调用一个shell脚本,并且在c中有一些变量,我希望将这些变量作为参数传递给shell脚本。我尝试使用系统调用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);
}

您必须构造一个字符串,其中包含系统要执行的完整命令行。最简单的方法可能是使用sprintf

对于初学者来说,这是一条捷径

但至少在unix系统中也有fork和exec的强大组合。如果您的参数已经是独立的字符串,这可能比真正复杂的格式规范更容易;更不用说为复杂的格式规范计算正确的缓冲区大小了

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);
}

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

返回状态为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);

下面这个程序对我很有效

#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-a x-b y-c z-d等等

我使用以下命令编写了C程序

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

执行

/公用设施名称-a x-b y-c z-d等等


为我工作

您是否尝试过在shell脚本中使用getopt,如图所示?…我假设您使用的是Linux?如果不是因为sprintfcmd、%s…、cmd…的古怪,我会投票支持它。。。。这是严格合法的吗?这是很多不必要的复制与sprintf。。。为什么不是我们的strlcat或者至少是strncat呢?或者,使用sprintf的结果来偏移cmd,然后一个接一个地打印参数?为什么要发布两次相同的答案?
#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);
}