How to Run a Linux Command and Redirect its output to a socket in C

I have a Linux socket server program. I need to run the commands sent by the client and return the output to client. Is there a quicker way?

I tried with
ptr=popen(command, "r"); and then
fgets(buf, size,ptr);
write buf to socket

fgets hangs for me.

Now, I would like to know if I can re-direct the output of popen() or system() to the client socket. How can I do that?

Thank you very much.

No, there is no way of directly outputting to the client socket. You need to modify your code to loop until no more data is available i.e. fgets() returns NULL. Using ls as an example, here is some pseudo code which should point you in the right direction:

FILE *fp;
char path[PATH_MAX];
...
fp = popen("ls", "r");
while (fgets(path, PATH_MAX, fp) != NULL) {
    # fprintf(stderr, "%s", path);
    write(sockfd, path, strlen(path));   
}

pclose(fp);   
...

You could also look at the source code for rexecd for inspiration.

I think you can redirect the output to a stream socket if you fork and exec rather than using popen. This is because the redirection has to happen before you run the program, not after.

{
  pid_t pid=fork();
  int st;

  if(pid < 0)
  {
    perror("Couldn't fork");
  }
  else if(pid == 0) /* child code, run in a seperate process */
  {
    dup2(sock, 1); /* Duplicate socket's FD over FD #1, aka stdout */
    dup2(sock, 0); /* Duplicate socket's FD over FD #0, aka stdin */
    close(sock); /* Only closes the child's copy.  And the stdin/stdout copies remain. */
    execlp("/bin/echo", "HEY GUYS ALJ AF MY FACE IS A ROTTORN BANANA");
    /* Code below will never happen unless exec fails */
    perror("Couldn't exec");
    exit(1);
  }
  else
  {
    close(sock); /* Parent doesn't need socket anymore */
    waitpid(pid, &st, 0); /* Wait for child to finish */
  }
}

Hi,

I don't know the your application completely.. But I think "nc" might be a good option for you.. It can execute an arbitarary command and send its output over the socket.. (you need not open this socket).. Refer to man page or visit http://roorkytech.blogspot.com/ for details of nc.

Thanks
-- Prasad