我试图从我的 C 代码执行命令行,但是当我到达 fgets() 函数时,我收到了 NULL 错误。
void executeCommand(char* cmd, char* output) {
FILE *fcommand;
char command_result[1000];
fcommand = popen(cmd, "r");
if (fcommand == NULL) {
printf("Fail: %s\n", cmd);
} else {
if (fgets(command_result, (sizeof(command_result)-1), fcommand) == NULL)
printf("Error !");
strcpy(output, command_result);
}
pclose(fcommand);
}
我的命令是:
java -jar <parameters>
为什么我从 fgets 得到 NULL 结果,尽管当我尝试在终端中执行相同的命令时,它按预期工作。
最佳答案
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.
简而言之,popen()
正在执行 fork()
并且您正尝试在 cmd< 调用程序之前从管道中读取数据
产生了输出,因此管道上没有数据,管道上的第一次读取将返回 EOF
,因此 fgets()
返回时没有获取数据。您要么需要 sleep ,要么进行轮询,要么进行阻塞读取。
关于c - fgets 为 popen 返回的 FILE 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15882799/