在c

时间:2016-04-27 19:59:52

标签: c linux grep exec

我正在尝试创建一个函数来获取有关执行它的进程的信息。基本上我必须执行ps -ef,然后使用grep (the pid of the process)过滤结果。问题是我必须使用exec执行此操作,使用ps -ef | grep pid会很容易。 目前我能够将ps的结果传递给父进程,但我不知道如何将其放入grep

在此代码中,我尝试将ps的输出作为stdin的{​​{1}},但坦率地说,我不知道我在做什么。我应该从管道中取出我得到的东西并以某种方式将其传递给grep

以下是代码:

grep

我从这段代码中获得的是执行时:它打印父进程的数量和冻结。如果我将 int main(){ /*Variables*/ int fd[2][2]; int cpid[2]; char spid[10]; int maxbuf=10000; char buffer[maxbuf]; char ch; int count; /********************/ sprintf(spid,"%d", getpid()); printf("%s\n", spid); if(pipe(fd[0])==-1){ perror("Pipe error"); exit(EXIT_FAILURE); } cpid[0]=fork(); switch(cpid[0]){ case -1: perror("Fork error"); exit(EXIT_FAILURE); case 0: if(pipe(fd[1])==-1){ perror("Pipe error"); exit(EXIT_FAILURE); } cpid[1]=fork(); switch(cpid[1]){ case -1: perror("Fork error"); exit(EXIT_FAILURE); case 0: close(fd[1][0]); close(1); dup(fd[1][1]); //sleep(1); //wait(NULL); execlp("ps","ps","-ef",(char *)0); perror("Error in ps command"); exit(EXIT_FAILURE); default: close(fd[1][1]); close(0); dup(fd[1][0]); close(fd[0][0]); close(1); dup(fd[0][1]); //sleep(1); //wait(NULL); execlp("grep","grep", spid, (char *)0); perror("Error in grep command"); exit(EXIT_FAILURE); } default: for (count=0;read(fd[0][0], &ch,1)==1 && count<maxbuf; count++){ buffer[count]=ch; } } exit(EXIT_SUCCESS); } 与进程的pid一起使用 我看到pstree表示如果冻结test───grep(如果我错了,请纠正我) 我知道有一些像grep这样的crapy部分,但我想关注buffer[maxbuff]问题。

感谢任何帮助,谢谢。

0 个答案:

没有答案