3

I have two C programs, Project1A.c and Project1B.c. I'm trying to use execl() to execute Project1A from inside Project1B but so far it's not working.

Project1B.c

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

int main ()
{
  pid_t pid;

  switch((pid = fork()))
  {
    case -1:
      printf("I'm sorry, fork failed\n");
      break;
    case 0:
      execl("Project1A.c", "./prog", NULL);
      printf("EXECL Unsucessfull");
      break;
    default:
      printf("This is some parent code\n");
      break;
  }
  printf("End of Program\n");

  return 0;
}
Taylor LeMaster
  • 133
  • 2
  • 9
  • 7
    You can't execute a C source file.You have to run a compiled program. – Fred Larson Mar 23 '17 at 13:56
  • 1
    You have to `wait` for the child process, as well as test return value of `exec` whether any error occurred. – dmi Mar 23 '17 at 14:01
  • 1
    A "C program" has very little to do with computers. It's an abstract description of instructions for an abstract machine. A *program* on the other hand, for real computers, has very little to do with C. A program is just a program. C is just one way to *create* programs, but it's not part of the result. – Kerrek SB Mar 23 '17 at 14:07
  • 1
    @dmi: There isn't much to test in the return value. If it succeeds, it doesn't return. If it returns, the return value is -1. Might not hurt to check `errno`, though, to see what the problem is. – Fred Larson Mar 23 '17 at 14:08
  • @Fred Larson, that's what I meant - to indicate whether exec has returned an error as from the description is not clear what exactly "does not work" mean – dmi Mar 23 '17 at 14:13
  • Try replacing `printf` with `perror` in the line `printf`"EXECL Unsuccessfull");` It should give you a bit more information on why the `execl` call failed. – Fred Larson Mar 23 '17 at 14:16
  • Your code works just fine for me if I replace `"Project1A.c"` with a valid executable program. – Fred Larson Mar 23 '17 at 14:37
  • So how would I turn "Project1A.c" into an executable program? – Taylor LeMaster Mar 23 '17 at 15:53
  • 1
    Compile it. Something like `cc -o Project1A Project1A.c`. – Fred Larson Mar 23 '17 at 19:59

1 Answers1

3

execl executes a binary file, meaning you cannot pass it Project1A.c and expect it to work. You need to compile it and execute the compile program.

Subsequent arguments to the function are command-line arguments, terminated by NULL. This means that your execl call corresponds to ./Project1A.c ./prog on a shell, which obviously doesn't work.

Instead, your execl call should be: execl("prog1A", NULL);.

On a side not, you could maybe run C code by running the compile command first using the system function and then running the compiled program with execl if the compilation was successful.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Lunar
  • 176
  • 8