0

In a C program, let's say i wann use Exec functions for executing a given program, for example if i wanna just try ls -l i'll do something like

args[0]="ls";
args[1]="-l";
args[2]=NULL;

...
execvp("ls", args); 

and it's all fine. Now what if i wanna also add the redirection to a file (or to stderr)? I'm stuck, it's obvious that adding >log.txt as a 3rd entry in the array won't work, but I don't know how to proceed.

And also, what if I wanna pass some Input parameters? What if i wanna execute a GCC command like "gcc -o out in redirection>log.txt" ?

[update from comment:]

It's a C program that simulate a shell which can "run strings", string that contains a command, a list o parameters, input and a redirection.

3
  • "what if I wanna pass some Input parameters?" - isn't the args array there for exactly that purpose? (if you want to pipe text to and from stdin/stdout, you'll need popen().) Commented Apr 27, 2014 at 10:38
  • possible duplicate of Redirect standard output to a file? Commented Apr 27, 2014 at 10:38
  • @OliCharlesworth Is there a guarantee not only the stream but also the file-descriptor is the same after freopen? Commented Apr 27, 2014 at 10:50

2 Answers 2

1

Just set up your file descriptors as the exec-d process shall find them and then do the exec.
For that you need open, dup2 and close.

All functions in the exec-family just replace the current process with whatever one you say.

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

2 Comments

thank you for the answer, i think i'm gettin the output part. This also applies to the input thing? Changing file descriptor of stdIn to the file i want to be the input.c of (for instance) gcc?
Yes, just set up whatever environment you want the new executable to inherit.
0

Run the command in a shell:

char * args[] = {
  "sh",
  "-c",
  "ls -l >out.ls 2>err.ls <in.ls",
  NULL
};

...

execvp(args[0], args); 
perror("execvp() failed");

2 Comments

Sorry to ask but i'm newbie, i didn't hinted in the OP that all this has to be written in a C program, do this solution works for what i'm doing? I't a C program that simulate a shell which can "run strings", string that contains a command, a list o parameters, input and a redirection. Suppose i have to study more for the SH thing, by now i never seen sh -c ...stuff
@ro.nin: For such requirements an approach as described by Deduplicator's answer (stackoverflow.com/a/23322407/694576) suit better.

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.