• How to capture output of child process in C programming

    Amit Member

    How to capture output of child process in C programming

  • Amit Member

    The easiest and least flexible way is to use popen():

    #define BUFSIZE 1024
    #include 
    
    main() {
      char buf[BUFSIZE];
      FILE *p = popen("/bin/who","r");
    
      while ( !(feof(p)) ) {
        fgets(buf,BUFSIZE,p);
        dowhateverwithdata(buf);
      }
      pclose(p);
    }
    

    Of course you can use fscanf() or whatever you want to get the actual datastream. Obviously this approach is limited in that you can ONLY read OR write to the spawned process, not both.

    Another, more flexible way, is (of course) much more complicated. I won’t go in to detail, but you can use a function called pipe() to create a pipe from a 2-element int array (i.e., int thing[2]; pipe(thing);) This makes the array into a pair of file descriptors, 0 is for reading, 1 is for writing. so for two-way communication you would need two pipes pointing opposite ways. Then you can use fork() to create a child process. Then, in the child, you can use dup2() to make the appropriate ends of your pipes into the stdin and stdout of your child. Then you can exec() the process you want in the child, and its stdin and stdout will be your pipes. In the parent, you can read the up pipe and write the down pipe and wait() and stuff like that.

    That approach may be a little beyond what you want or need from this thing. If you want code that does that stuff, you can mail me and i’ll throw something together.

    BUT!

    Have you thought about this? There are a fair number of standard UNIX C functions that do things with the utmp. That’s really what you’re after, isn’t it? Well yeah, since you want to monitor who’s logged in. You can do all sorts of fancy stuff doing direct utmp operations. That would probably also offer more flexibility as far as user monitoring is concerned. You get back cooler data too, as i remember. I once wrote a program like this and all my friends wanted it. Unfortunately shortly after that my account at that school got revoked– they thought i was hacking, just cos i allocated a whole bunch of shared memory and didnt put it back and crashed the system 🙁 But if you’re interested in that approach, look in to the getutent() and related man pages.

Viewing 1 reply thread
  • You must be logged in to reply to this topic.
en_USEnglish