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.
If you are new to fork, graphical representation about fork and exec might be helpful to you.
Depiction of
fork()
As you might have already read in a tutorial, after calling
fork()
a duplicate copy of the existing program is created, and theexec()
after that replaces that copy with the new program, which you pass to it as arguments. Two execution units for two programs will be running afterfork()
.Yes. Read first the documentation (
man
page), e.g. of fork(2), exec(3), system(3). Quite probably you have that documentation locally on your computer, using man(1). Notice thatsystem
usessh
(thru bash(1) or dash(1)), because it isfork
-ing, execve(2)-ing and waitpid(2)-ing the/bin/sh
POSIX shell.I think that
fork
is difficult to understand because on success it returns "twice". I won't try to explain it here (I'll need many pages for that). I recommend reading fork (system call) wikipage at first. Then, read some good Linux programming book, e.g Advanced Linux Programming (freely downloadable).Read also about Virtual Address Space, and proc(5).
You could also read Operating Systems: Three Easy Pieces for a more general view.
Won't
system()
be enough for you?For the most simple case you should two compiled programs in one directory:
In second program you just need to call
system("hello");