Executing a shell command and reading its output in C

I am trying to create a function that takes a shell command as an argument, uses fork to create a new process that executes the command. I also want to redirect the standard output of the command so that the calling function can read it using the 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'm not sure how to return a file pointer that can be used to read the output of a command. Also, is this the correct way to execute a command on a shell?

ps. I read about popen, but there is a good reason why I cannot use it, so I have to implement this functionality myself.

thanks

+4
source share
2 answers

One mistake in this code is that you are assigning a pid variable that is not declared anywhere. And pid will always be 1 in the parent, because the written code is equivalent to pid=(fork()==0) , and not (pid=fork())==0 .

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

The answer to your real question is to use fdopen .

+4
source

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

+1
source

Source: https://habr.com/ru/post/1343455/


All Articles