Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you call a C program from within another C program

Tags:

c

fork

exec

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;
}
like image 244
Taylor LeMaster Avatar asked Jul 02 '26 08:07

Taylor LeMaster


1 Answers

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.

like image 143
Lunar Avatar answered Jul 03 '26 22:07

Lunar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!