fgets returning error for FILE returned by popen

試著忘記壹切 提交于 2019-12-10 15:44:11

问题


I'm trying to execute a command line from my C code, but when I get to the fgets() function, I got a NULL error.

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);
}

And my command is:

java -jar <parameters>

Why do I have a NULL result from fgets, despite that when I try to execute the same command in a terminal, it works as expected.


回答1:


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.

In short, the popen() is doing a fork() and you're trying to read from the pipe before the program evoked by cmd has produced output, therefor there is no data on the pipe and the first read on the pipe will return EOF, so fgets() returns without getting data. You either need to sleep, do a poll or do a blocking read.



来源:https://stackoverflow.com/questions/15882799/fgets-returning-error-for-file-returned-by-popen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!