从C应用程序运行shell脚本
我正在用C编写一个应用程序(基于CLI),我希望能够运行一个shell脚本来执行系统级命令(这是一个特定于OSX的应用程序)。有办法做到这一点吗? 我试过system(),但它说它在c99时无效从C应用程序运行shell脚本,c,macos,shell,popen,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
if (response == 'Y' || response == 'y') {
system("Support/script.sh");
system("Support/deps.sh");
printf("Success");
} else {
printf("Good Bye!\n\n");
}
检查您当前的工作目录。pwd中似乎不存在te
Support
文件夹MacOSX
,一个基于objective-C
的系统调用应该可以使用
如果您需要,下面是我使用popen
的示例程序。(只是我的一段代码..不完整)
“它”?怎么说是无效的?这是BS,
system()
甚至在C89标准中。无效吗?实际的错误信息是什么?您是否包含了stdlib.h?我所说的“it”是指xcode,是的,我包含了stdlib.hAn替代方法是使用popen
+fread
+pclose
,如果没有特定的错误消息,我们就无法真正了解出了什么问题。
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;