1

I'm looking to make a program with the purpose of compiling another. The purpose being using exec to run gcc. I have to use execve and what I have is:

#include <unistd.h>
#include <sys/types.h>

int main(int argc, char* argv[], char* envp[])
{
  argv[0] = "gcc";
  execve("/usr/bin/gcc" , argv, envp);
  return 0;
}

By doing

gcc -Wall p3p4.c -o run

It compiles without problems, but when doing

./run p3p1.c

To try and compile another one, this happens:

run: error trying to exec 'cc1': execvp: No such file or directory

EDIT:

As advised, when adding the line:

argv[0] = "gcc";

The program manages to work. Thank you for the input.

Aleister
  • 99
  • 1
  • 8
  • 4
    Why not use [Make](http://en.wikipedia.org/wiki/Make_(software))? – Chris Seymour Mar 04 '13 at 13:53
  • The `argv` you get in `main` and the `argv` you pass to `execve` need to be different. It needs to be terminated with a null pointer, and `argv[0]` is typically the name of the program being executed. – slugonamission Mar 04 '13 at 13:55
  • Y dont you use system() ?? – Charan Pai Mar 04 '13 at 13:56
  • @slugonamission `argv` should already be terminated by a `NULL` pointer. – Some programmer dude Mar 04 '13 at 13:57
  • @slugonamission The vector is already NULL-terminated. – cnicutar Mar 04 '13 at 13:58
  • Try running `/usr/bin/gcc p3p1.c` on the command line and see what happens. Do you _have_ a file named `p3p1.c` in the current directory? – Some programmer dude Mar 04 '13 at 13:58
  • It seems your lecturer is asking you to write a *compiler*, as you described the requirements of your program "to make a program with the purpose of compiling another". Are you sure your program fulfills these requirements? You can't just wrap a compiler and call your program a compiler. – autistic Mar 04 '13 at 14:08
  • Running that on the current directory compiles the program p3p1.c without issues. I have edited the post to reflect the latest issue. And this is what my lecturer is asking. The purpose of the exercise is to use the system call exec to redirect the program, not write a full compiler. – Aleister Mar 04 '13 at 14:09

2 Answers2

3

Try setting argv[0] like a well-behaved program:

argv[0] = "gcc";
execve("/usr/bin/gcc" , argv, envp);

run: error trying to exec 'cc1':

This is apparently what gcc tries to run when it finds something unexpected in argv[0].

cnicutar
  • 178,505
  • 25
  • 365
  • 392
0

excve tells you that he didn't find gcc. Try

execvpe ("gcc", argv, envp);

Note that here envp is useless (and not POSIX) ; you can safely remove envp from main() and call

execvp ("gcc", argv);
Edouard Thiel
  • 5,878
  • 25
  • 33