Invoking a function (main()) from a binary file in C
- by Dhara Darji
I have simple c program like, my_bin.c:
#include <stdio.h>
int main()
{
printf("Success!\n");
return 0;
}
I compile it with gcc and got executable: my_bin.
Now I want to invoke main (or run this my_bin) using another C program. That I did with mmap and function pointer like this:
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
int main()
{
void (*fun)();
int fd;
int *map;
fd = open("./my_bin", O_RDONLY);
map = mmap(0, 8378, PROT_READ, MAP_SHARED, fd, 0);
fun = map;
fun();
return 0;
}
PS: I went through some tutorial, for how to read binary file and execute.
But this gives Seg fault, any help appreciated! Thanks!