如何在C中grep? [英] How to grep in C?

查看:244
本文介绍了如何在C中grep?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将execlp取消使用grep
这段代码有什么问题

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;
 }

有问题:/bin/grep :(标准输入):输入/输出错误

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

推荐答案

您可能在Linux或POSIX上使用

You might use (on Linux or POSIX) the popen(3) function. Don't forget to pclose (not fclose) such a stream.

在发现在Linux上运行telnet的进程的特定情况下,您甚至不需要为此分叉另一个进程(并且,如果您愿意,请使用 proc(5)).例如,您将使用 opendir(3) readdir(3)和相关功能,以扫描/proc/进行查找以数字开头的目录(因此对应于进程).比每个这样的目录,例如/proc/1234/您可以阅读/proc/1234/cmdline readlink(2)/proc/1234/exe.您将使用 snprintf(3)构造对应的字符串这些文件路径.

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.

您的程序对 fork(2)管道(2) dup2(2),并且您可能需要多次调用fork并使用 waitpid(2).

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).

阅读 ALP (可免费下载)或其他有关Linux编程的书.

Read ALP (freely downloadable) or some other book on Linux programming.

考虑使用 strace(1)(可能与-f)以了解发生了什么.不要忘记编译所有警告和调试信息gcc -Wall -Wextra -g并使用gdb调试器(小心,它可用于多进程程序).

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).

关于您的新编辑(如何在C语言中使用grep"), grep(1)使用正则表达式,您可以使用

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.

这篇关于如何在C中grep?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆