PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 22, 2022

[FIXED] How to get output of exec()?

 July 22, 2022     c, exec, fork, linux, unix     No comments   

Issue

How do I get the output of a program ran by exec(). Let's say I have this code:

int main(int argc, char ** argv) {
    int fid = fork();
    if(fid == 0) {
        execlp("ls", "ls", NULL);
    }
    wait();
    return 0;
}

How can the parent process get the output of the ls command?


Solution

The exec family of functions completely replaces the current process. However, they do not close file descriptors unless they marked close-on-exec. Thus, the typical way to do this is to create a pipe where the read side belongs to the parent and the write side belongs to the child.

This would look something like this (error checking omitted and obviously inefficient):

#include <stdint.h>
#include <sys/wait.h>
#include <unistd.h>

int main(int argc, char ** argv) {
    int pipefd[2];
    int status;
    uint8_t buf[256];

    pipe(pipefd);

    int fid = fork();
    if(fid == 0) {
        close(pipefd[0]);
        dup2(pipefd[1], 1);
        close(pipefd[1]);
        execlp("ls", "ls", NULL);
    }
    close(pipefd[1]);

    while (read(pipefd[0], buf, 1) > 0)
        write(1, buf, 1);
    wait(&status);
    return 0;
}

Note that to attach the pipe file descriptor to standard output (FD 1), you need to use dup2. You also need to close the ends of the pipe you're not using, or you may never end up reaching end of file.

If you're interested in the exit status, wait (or waitpid) will provide that for you; see the manual page for how to determine if it exited normally and if so, what that status was.



Answered By - bk2204
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing