sheredom / subprocess.h

🐜 single header process launching solution for C and C++
The Unlicense
1.1k stars 97 forks source link

unable to read from stdout #53

Closed divyanshu0045 closed 2 years ago

divyanshu0045 commented 2 years ago

Hi I tried a sample program with cat command but was not able to get required output. The code just hangs at first call to fgets. Am I doing something wrong?

#include <stdio.h>
#include <string.h>
#include "subprocess.h"
int main()
{
    const char *command_line[] = {"/usr/bin/cat", NULL};
    struct subprocess_s subprocess;
    int result = subprocess_create(command_line, 0, &subprocess);
    if (0 != result) {
        puts("an error occurred!");
        return 1;
    }
    FILE* p_stdout = subprocess_stdout(&subprocess);
    FILE* p_stdin = subprocess_stdin(&subprocess);
    FILE* p_stderr = subprocess_stderr(&subprocess);
    char msg[] = "test";
    char resp[2000] = {0};

    puts(msg);
    fputs(msg, p_stdin);

    memset(resp, 0, 2000);
    fgets(resp, 4, p_stdout);
    puts(resp);

    puts(msg);
    fputs(msg, p_stdin);

    memset(resp, 0, 2000);
    fgets(resp, 4, p_stdout);
    puts(resp);

    getchar();
    return 0;
}
orgads commented 2 years ago

You probably need to add fflush after writes.

orgads commented 2 years ago

And you also need to read 5 chars (to include the terminating NULL).

Fixed version:

#include <stdio.h>
#include <string.h>
#include "subprocess.h"
int main()
{
    const char *command_line[] = {"/usr/bin/cat", NULL};
    struct subprocess_s subprocess;
    int result = subprocess_create(command_line, 0, &subprocess);
    if (0 != result) {
        puts("an error occurred!");
        return 1;
    }
    FILE* p_stdout = subprocess_stdout(&subprocess);
    FILE* p_stdin = subprocess_stdin(&subprocess);
    FILE* p_stderr = subprocess_stderr(&subprocess);
    char msg[] = "test";
    char resp[2000] = {0};

    puts(msg);
    fputs(msg, p_stdin);
    fflush(p_stdin);

    memset(resp, 0, 2000);
    fgets(resp, 5, p_stdout);
    puts(resp);

    puts(msg);
    fputs(msg, p_stdin);
    fflush(p_stdin);

    memset(resp, 0, 2000);
    fgets(resp, 5, p_stdout);
    puts(resp);

    getchar();
    return 0;
}
sheredom commented 2 years ago

Thanks for helping @orgads !