You should read Advanced Linux Programming (a bit old, but freely available). You probably want (in the traditional way, like most shells do):
perhaps catch SIGCHLD
(set the signal handler before fork
, see signal(7) & signal-safety(7)...)
call fork(2) to create a new process. Be sure to check all three cases (failure with a negative returned pid_t
, child with a 0 pid_t
, parent with a positive pid_t
). If you want to communicate with that process, use pipe(2) (read about pipe(7)...) before the fork
.
in the child process, close some useless file descriptors, then run some exec
function (or the underlying execve(2)) to run the needed program (e.g. /bin/ls
)
call (in the parent, perhaps after having got a SIGCHLD
) wait(2) or waitpid(2) or related functions.
This is very usual. Several chapters of Advanced Linux Programming are explaining it better.
There is no need to use threads in your case.
However, notice that the role of ls
and cat
could be accomplished with various system calls (listed in syscalls(2)...), notably read(2) & stat(2). You might not even need to run other processes. See also opendir(3) & readdir(3)
Perhaps (notably if you communicate with several processes thru several pipe(7)-s) you might want to have some event loop using poll(2) (or the older select(2)
). Some libraries provide an event loop (notably all GUI widget libraries).