Liseł Liseł - 2 months ago 15
C Question

Run a system command with system() and send output

So what I am trying to do is to invoke a system command with

system()
function and then whatever its output is I would like to take it and send it over to the client (socket connection).

Client can send various messages. It can be
ls
but it might be even
qwerty
. I would like to take the ouput and place it in the
write()
function as a
const void* buffer
argument. I have seen this topic but I can get it done to work. So far I thought it could go somewhere of these lines but whatever I tried it did not work.

/* buffer is message from the client: ls, ls -l, whatever*/
system(buffer)
fp = popen(buffer, "r");
if(fp == NULL)
printf("Failed ot run command\n");

while(fgets(path, sizeof(path), fp) != NULL) {
//modify output here?
}
pclose(fp);
write(socket_fd, output, strlen(buffer));

Answer

You should only use popen() and not system() as it describes in the question you linked.

The path variable in the question you linked seems to be misnamed. It contains the output of the system call. You can rename it to output if you wish.

write() takes the length of the buffer you are sending it. In this case, that will be the length of output, not the length of buffer.

Putting this all together gives the following:

char output[1035];
fp = popen(buffer, "r");
if(fp == NULL)
   printf("Failed ot run command\n");

while(fgets(output, sizeof(output), fp) != NULL) {
    write(socket_fd, output, strlen(output));
}
pclose(fp);