-5

unsing execlp to grep
what problem this code

int main(){
      int fd[2];
      pid_t child_pid;

      pipe(fd);

      if((child_pid = fork())<0){
          perror("fork error");
          exit(0);
      }
      if(child_pid >0){
          close(fd[0]);
          execlp("/bin/ps", "/bin/ps", "-ef", NULL);
      }
      else{
          close(fd[1]);
          execlp("/bin/grep", "/bin/grep", "root", NULL);
      }
      return 0;
 }

have problem: /bin/grep: (standard input) : Input/output error

Ajay Brahmakshatriya
  • 8,993
  • 3
  • 26
  • 49
st_Prog.
  • 19
  • 2
  • 5
  • 1
    Is it some homework (to code in C the *equivalent* of `ps -ef | grep telnet`) or are you genuinely seeking in a C program what processes are using `telnet` ? SO is not a *do-my-homework* service. – Basile Starynkevitch Nov 04 '17 at 12:05
  • 1
    Your question lacks some Linux or POSIX tag. – Basile Starynkevitch Nov 04 '17 at 12:08
  • SO is not a *fix-my-bug* or *do-my-homework* service. – Basile Starynkevitch Nov 04 '17 at 12:29
  • No, your problem is a misunderstanding of how Linux processes work (and is not really related to `grep`, `ps`, `telnet`). My answer provided several clues, but I won't do your homework. Spend a few hours reading ALP. – Basile Starynkevitch Nov 04 '17 at 12:33
  • But you could replace `ps` with `echo `, `grep` with `wc`, and `telnet` with `-l` and your program still remains wrong. So you are not specifically asking about `grep`. ALP has several chapters related to your question, you need to read them. – Basile Starynkevitch Nov 04 '17 at 12:37

1 Answers1

2

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.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547