【问题标题】:Run a shell script from C application从 C 应用程序运行 shell 脚本
【发布时间】:2013-12-17 12:43:02
【问题描述】:

我正在用 C 编写一个应用程序(基于 CLI),并且我希望能够运行一个 shell 脚本来执行系统级命令(它是一个 OSX 特定的应用程序)。有没有办法做到这一点? 我试过 system() 但它说它从 c99 开始无效。

if (response == 'Y' || response == 'y') {
        system("Support/script.sh");
        system("Support/deps.sh");
        printf("Success");
    } else {
        printf("Good Bye!\n\n");
    }

【问题讨论】:

  • “它”?什么说无效?那是废话,system() 甚至在 C89 标准中。
  • 无效?实际的错误信息是什么?你包括stdlib.h吗?
  • “它”是指 xcode,是的,我确实包含了 stdlib.h
  • 另一种方法是使用popen + fread + pclose
  • 如果没有具体的错误信息,我们就无法知道发生了什么问题。

标签: c macos shell popen


【解决方案1】:

检查您当前的工作目录。看起来 te Support 文件夹在密码中不存在。 Mac OS X,基于objective-C,应该与系统调用一起使用。

这是我使用popen 的示例程序,如果您需要的话。 (只是我的代码的一个 sn-p.. 不完整)

char unix_script[1000];
memset(unix_script,'\0',sizeof(unix_script));
snprintf(unix_script,
          sizeof(unix_script),
          "ksh /usr/mahesh/sessioN.ksh %s %s %s %s %s",
          userId,
          password,
          database,
          sbcr_id,
          session_id);
char *COMMAND = unix_script,*readLine, *tmp, *commandResult = "";
FILE * fp;
int status;

fp = popen(COMMAND, "w");

if (fp == NULL) {
      perror("Command execution failed");
      exit(1);
}

//printf("Printing the command output....");
while ((fscanf(fp, "%s", &readLine)) != EOF) {
      tmp = (char *) realloc(commandResult, strlen(readLine));
      commandResult = tmp;
      strcpy(commandResult, readLine);
}
printf("\n output =\n %s\n",commandResult);
status = pclose(fp);
//printf ("Command %s exit status code = %d\n", COMMAND, status);
return status;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 2011-07-15
    • 1970-01-01
    相关资源
    最近更新 更多