You can execute a binary in your own program with the exec-family.
try "man execlp".
Be aware, if you execute a binary with an exec* command you will override your old program,
so you have to fork() a new process if you want anything from the executed binary.
Here is an example of execlp() and fork():
/*
"prg" is the binary to execute
"arg1" is an argument1 for the binary
"arg2" is an argument2 for the binary
"type" controls the output: 1 is stdout, 2 is stderr
The funtion returns:
-1 in case of an incorrect "type"
-2 if no pipe could be created
-3 if a process couldn't be forked
str a string from stdout or stderr.
*/
char* execSub(char *prg, char *arg1, char *arg2, int type)
{
pid_t Pid;
int pipefd[2];
char buffer[5000];
int anz, i, status;
char *str;
status=0;
anz=0;
str=NULL;
/* pipe is | */
if(pipe(pipefd)==-1){ //PIPE-error
str=(char*) malloc(2);
strcpy(str, "-2");
return str;}
switch((Pid=fork())) {
case 0:{ //---------------Child
close(pipefd[0]);
if(type==0)
close(1);
if(type==1)
close(2);
else{
str=(char*) malloc(2);
strcpy(str, "-1");
return str;}
dup(pipefd[1]);
execlp(prg, prg, arg1, arg2, NULL); //prg gets executed
exit(0);
}
case -1: { //FORK-error
str=(char*) malloc(2);
strcpy(str, "-3");
return str;}
default:{ //---------------Parent
wait(&status);
close(pipefd[1]);
printf(" executing %s ", prg);
while((anz=read(pipefd[0],buffer,5000))>0){
if(str==NULL)
str=(char*) calloc((anz+1), sizeof(anz));
else if(buffer==NULL && str !=NULL)
str=(char*) realloc(sizeof(anz+1));
for(i=0; i<anz;i++)
str[i]=buffer[i];
}
}
return str;
}
}
I hope this helps.
|