You might use (on Linux or POSIX) the popen(3) function. Don't forget to pclose
(not fclose
) such a stream.
In your particular case of finding a process running telnet
on Linux, you don't even need to fork another process for that (and if you wanted to, use pgrep(1)). You could directly use /proc/
(see proc(5)). You would for example use opendir(3), readdir(3) and related functions to scan /proc/
to find directories starting with a number (so corresponding to processes). Than for each such directory, e.g. /proc/1234/
you could read /proc/1234/cmdline
or readlink(2) its /proc/1234/exe
. You'll use snprintf(3) to construct strings corresponding to those file paths.
Your program shows some confusion about fork(2), pipe(2), execve(2). You might want to use dup2(2) and you probably need to call fork
more than once and use waitpid(2).
Read ALP (freely downloadable) or some other book on Linux programming.
Consider using strace(1) (probably with -f
) to understand what is going on. Don't forget to compile with all warnings and debug info gcc -Wall -Wextra -g
and to use the gdb
debugger (with care, it is usable on multi-process programs).
Regarding your new edit ("how to grep in C"), grep(1) uses regular expressions, and you can use regex(3) on POSIX to use them in your C code. You don't need to fork a new process.