Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write a C program to execute another program?

Tags:

c

linux

In linux, I would like to write a C program that launches another program. When the program runs, the shell will be waiting for you to input a command that you have defined in you program. This command will launch the second program.

For example, assume there is a simple C program called "hello" in the same directory as the invoking program. The "hello" program prints the output "hello, world". The first program would be run and the user would input the command "hello." The "hello" program would be executed and "hello, world." would be output to the shell.

I have done some search, and people suggested the "fork()" and "exec()" functions. Others said to use "system()". I have no knowledge about these functions. How do I call these functions? Are they appropriate to use?

Example code with explanations would be most helpful. Other answers are also welcome. Your help is greatly appreciated.

like image 508
wa-ha Avatar asked Mar 28 '11 14:03

wa-ha


People also ask

How do you call a program from another program?

u can use submit statement to call a program . range_line LIKE LINE OF range_tab. APPEND rspar_line TO rspar_tab. APPEND range_line TO range_tab.

What are the steps to execute program?

The following steps are involved in the execution of a program: - Fetch: The control unit is given an instruction. - Decode: The control unit then decodes the newly received instruction. - Execute: During the execution the Control unit first commands the correct part of hardware to take action.

Can a program be invoked from another program?

As I know, any address in a program only belongs itself, meaning that you can't invoke a function of another program thought its address. Data is code, code is data. As soon as your exploit payload (i.e. machine code) is read into memory by the process you're attacking, it has an address in the target process.


1 Answers

#include <stdio.h> #include <stdlib.h> #include <unistd.h> /* for fork */ #include <sys/types.h> /* for pid_t */ #include <sys/wait.h> /* for wait */  int main() {     /*Spawn a child to run the program.*/     pid_t pid=fork();     if (pid==0) { /* child process */         static char *argv[]={"echo","Foo is my name.",NULL};         execv("/bin/echo",argv);         exit(127); /* only if execv fails */     }     else { /* pid!=0; parent process */         waitpid(pid,0,0); /* wait for child to exit */     }     return 0; } 
like image 186
Svisstack Avatar answered Sep 24 '22 14:09

Svisstack