Badea Sorin
Badea Sorin

Reputation: 174

How to execute a bash command in C and retrieve output?

I'm trying to execute a bash command from c and retrieve and show the result. I've tried with system but it doesn't work. My code looks like:

char command[200];
sprintf(command,"lsof -iTCP:%d | cut -d\"\" -f1 | tail -1",port);
printf("Port %d is open\n and is listened by %s",port,system(command));

Please help. I need this .

Upvotes: 4

Views: 7133

Answers (2)

Jarek
Jarek

Reputation: 1330

system(command) returns the return code of the command, not its output. If you want to read the output of a command, you should use popen This returns a file descriptor to the output, which you can read from just like a normal file.

Upvotes: 1

sehe
sehe

Reputation: 393039

Edit aside from the actual question, I'd be using

sudo netstat -tlpn

(shows the processes that are listening on TCP ports, not resolving the ports/addresses)

Perhaps combine it with a bit of grep:

sudo netstat -tlpn | grep :7761

to find where port :7761 is being listened?


You can use popen.

With popen you get the benefit that you receive the process output asynchronously (you will be able to stop processing if the answer is on the first line of output without having to wait for the subprocess to complete; simply pclose and the subprocess will die with SIGPIPE)

A sample straight from the Standards Documentation:

The following example demonstrates the use of popen() and pclose() to execute the command ls * in order to obtain a list of files in the current directory:

#include <stdio.h>
...


FILE *fp;
int status;
char path[PATH_MAX];


fp = popen("ls *", "r");
if (fp == NULL)
    /* Handle error */;


while (fgets(path, PATH_MAX, fp) != NULL)
    printf("%s", path);


status = pclose(fp);
if (status == -1) {
    /* Error reported by pclose() */
    ...
} else {
    /* Use macros described under wait() to inspect `status' in order
       to determine success/failure of command executed by popen() */
    ...
}

Upvotes: 6

Related Questions