Search code examples
clinuxtcpposixpopen

How to read the stdout from the popen() function and store it in the char array in C language?


Well, I got stuck in sending stdout output to the array. How can I solve this issue? I need to send back the bash command output with the code of execution to the client from the server. The protocol is TCP. Thank you!

     void func(int sockfd)
     { 
        char buff[MAX]; 
        for (;;) 
        { 
            bzero(buff, MAX); 
            read(sockfd, buff, sizeof(buff)); 
            printf("From client: %s\n", buff);
            if (strncmp("exit", buff, 4) == 0) 
            { 
                printf("Server Exit...\n"); 
                write(sockfd, buff, sizeof(buff));
                break; 
            } 
            FILE *cmd=popen(buff,"r");
            while (fgets(buff, sizeof(buff), cmd))
            strcpy(buff,cmd);
            pclose(cmd);
            write(sockfd, buff, sizeof(buff)); 
            my_itoa(system(buff),buff);
            write(sockfd, buff, sizeof(buff));          
        } 
     } 

Solution

  • I guess you want to send back to the client your execution result of bash command. You can change your code to write to sockfd every time you get a line of characters from cmd.

    FILE* cmd=popen(buff, "r");
    while(fgets(buff, sizeof(buff), cmd))
    {
      write(sockfd, buff, strlen(buff));  // sizeof() will write more than you actually read.
    }
    pclose(cmd);