4

I am trying to create a function which takes a shell command as an argument , uses fork to spawn a new process which executes the command. I also want to redirect the standard output of the command so the caller of the function can read it using a FILE* pointer.

static FILE* runCommand(char* command){
    int pfd[2];

    if(pipe(pfd)<0)     
        return NULL;

    if(pid=fork()==0){ //child
        close(pfd[0]);
        dup2(pfd[1],1); //redirect output to pipe for writing

        execlp(command,(char*)0);
    }

    close(pfd[1]);

    //return a file pointer/descriptor here?

}

I am not sure how to return a file pointer which can be used to read the output of the command. Also is that the correct way to execute a command on the shell?

ps. I read about popen but there is a good reason I can't use it, thus I have to implement this functionality myself.

Thank you

1
  • It seems popen is calling malloc ( I can see that cause I have overrided malloc ) and that complicates things for my project. That's why I'd prefer to not call popen. Commented Mar 12, 2011 at 17:53

2 Answers 2

4

One bug in that code is that you assign to a variable pid that is not declared anywhere. And pid will always be 1 in the parent, because the code as written is equivalent to pid=(fork()==0) rather than (pid=fork())==0.

You should also close pfd[1] after the dup2 call. And for good measure, check for errors from dup2 and execlp.

The answer to your real question is to use fdopen.

Sign up to request clarification or add additional context in comments.

Comments

1

Use fdopen to associate an existing file descriptor with a FILE * object. Everything else looks pretty good.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.