c - 从 C 应用程序运行 shell 脚本

标签 c macos shell popen

我正在用 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");
    }

最佳答案

检查您当前的工作目录。密码中似乎不存在 Support 文件夹。 Mac OS X,一个基于 objective-C 的系统调用。

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

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;

关于c - 从 C 应用程序运行 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20634478/

相关文章:

javascript - Iframe 尝试从安全来源与其顶级框架不同的文档调用 getUserMedia

python - pandas from mac ports ImportError : No module named io. 数据

Ruby:检查连通性

c - 我想在 IAR 工作台编译器中将数据从 long 转换为 ASCII

从定义中创建字符串文字

macos - 打开/查看 Firebird 数据库的最简单方法是什么?

multithreading - 多线程 BASH 编程 - 通用方法?

c - postfix 评估器不工作

c++ - 伙伴分配算法 - 起始堆地址

c - 如何将时间(NULL)生成的随机种子存储在文本文件中?