Help write a program that should search and count the number of processes by name (for example: "my-proc").

I understand:

  1. Browse the directories in the "/ proc /" directory.

  2. In each of them, read the file "comm" and compare it with the name of the process we are looking for.

ps How to implement in C?

  • one
    And what are the difficulties? opendir(); while(readdir()) { open(); read(); if(memcmp()) n++; close(); } printf n; - Mike
  • @Mike More in any way? =) - Andrey
  • No, otherwise it will be a job for asking, which is not welcome at SO. And actually all the required functions are listed, it remains to get some variables, to see in Google how these functions are used - Mike
  • @Mike All zashib, passed the task, in fact, your method ... - Andrey

2 answers 2

Similar to the first answer:

 ps ax | grep my-proc | wc -l 

ps - gives a list of ALL processors grep - filters by the given name wc - counts how many lines are obtained

    And so, this task was completed using opendir fopen, etc.

    But what solution did they show me:

     #include <stdio.h> #include <unistd.h> int main() { system("pidof -c genenv | wc -w"); } 

    Can someone explain what is happening?

    ps genenv - the name of the process, the number of which you want to count

    • one
      Read man pidof and man wc. / In short, pidof -c NAME (for example, pidof -c bash ) will display a list of PID processes with that name. The wc -w command will calculate the number of words in this list - avp