-1

Is The benefit of using popen is only to read the ouput produced by a command or there are some more benefits or advantages of popen over system.

Consider two programs below:

Program 1:

#include <stdio.h>

int main()
{
    FILE *more,*who;

    if (!(more = popen("more", "w")))
    {
            printf("Command `more` not found!");
            return -1;
    }
    if (!(who = popen("who", "r")))
    {
            printf("Command `who` not found!");
            return -1;
    }

    while (!feof(who))
    {
            char buffer[100];
            if (fgets(buffer, 100, who) != NULL)
            {
                    fputs(buffer, more);
            }
    }

    fclose(more);
    fclose(who);
  return 0;
 }

Program 2:

#include <unistd.h>
int main()
{
    system("who|more");
    return 0;
}

Why should i use Program1 if i can do the same thing in one line as done in Program2.

mSatyam
  • 531
  • 7
  • 25
  • 1
    If you did a little research, you would have come across [this Stack Overflow thread](http://stackoverflow.com/questions/8538324/what-is-the-difference-between-popen-and-system-in-c). – Anish Ramaswamy May 07 '13 at 06:46
  • 1
    Note that you should use pclose() on file descriptors you opened with popen(). – Alexis Wilke Nov 16 '13 at 12:11

1 Answers1

4

The two programs you have provided as examples are not equivalent. popen gives you a pair of file handles you can use to read and write input and output to and from stdin/stdout of the running process in an interactive manner. The system call is merely executing that and redirecting stdin of the current process to that of the invoked child process, and stdout of that process to stdout of the current (host) process.

It depends what you are trying to achieve, in general. If your goal is simply to run a command, system works fine. If you're interested in reading its output in a programmatic manner and processing it (and possibly generating more input), then popen is going to work better.

Gian
  • 13,735
  • 44
  • 51
  • From the popen(3) documentation: `Since a pipe is by definition unidirectional, the type argument may specify only reading or writing, not both` -- you read on one side and you write on the other. Within one program you cannot read and write on the pipe. It is unidirectional by definition. You've got to use pipe(2) to achieve that feat. – Alexis Wilke Nov 16 '13 at 12:06