我正在用 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/