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.

alk
  • 69,737
  • 10
  • 105
  • 255
ro.nin
  • 121
  • 5
  • 13
  • "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()`.) – The Paramagnetic Croissant Apr 27 '14 at 10:38
  • possible duplicate of [Redirect standard output to a file?](http://stackoverflow.com/questions/23135577/redirect-standard-output-to-a-file) – Oliver Charlesworth Apr 27 '14 at 10:38
  • @OliCharlesworth Is there a guarantee not only the stream but also the file-descriptor is the same after `freopen`? – Deduplicator Apr 27 '14 at 10:50

2 Answers2

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.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • 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? – ro.nin Apr 27 '14 at 11:25
  • Yes, just set up whatever environment you want the new executable to inherit. – Deduplicator Apr 27 '14 at 11:33
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");
alk
  • 69,737
  • 10
  • 105
  • 255
  • 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 Apr 27 '14 at 11:06
  • @ro.nin: For such requirements an approach as described by *Deduplicator*'s answer (http://stackoverflow.com/a/23322407/694576) suit better. – alk Apr 27 '14 at 11:09