0

私はKubuntuを使用していますが、他のライブラリは使用したくありません。Linux関数しか使用できません。ライブラリhttp://procps.sourceforge.net/があることは知っていますが、それは重要ではありません。ログに記録されたユーザーが所有するプロセスをprintfし、それらの日付、親プロセスID、およびユーザー名を表示したいのですが、Cでそれを行う方法は?

4

4 に答える 4

1

system("ps -aef | grep username");ユーザーが所有するすべてのプロセスを取得します。

于 2013-01-28T12:43:15.740 に答える
1

から読むことをお勧めし/procます。proc ファイルシステムは、Linux に実装されている最高のファイルシステムです。

そうでない場合は、(現在のプロセスのリストを取得するための) 独自のシステム コールを実装するカーネル モジュールを作成して、ユーザー空間プログラムから呼び出すことができるようにすることを検討できます。

/* ProcessList.c 
    Robert Love Chapter 3
    */
    #include < linux/kernel.h >
    #include < linux/sched.h >
    #include < linux/module.h >

    int init_module(void)
    {
    struct task_struct *task;
    for_each_process(task)
    {
    printk("%s [%d]\n",task->comm , task->pid);
    }

    return 0;
    }

    void cleanup_module(void)
    {
    printk(KERN_INFO "Cleaning Up.\n");
    }

上記のコードは、こちらの記事から抜粋したものです。

于 2013-01-28T13:59:34.417 に答える
1

これらの情報は に保存され/procます: 各プロセスには、その PID として名前が付けられた独自のディレクトリがあります。

これらすべてのディレクトリを繰り返し処理し、必要なデータを収集する必要があります。それpsがそうです。

于 2013-01-28T12:50:51.520 に答える
1

/procフォルダをスキャンする必要があると思います。始め方についてご紹介します。申し訳ありませんが、リクエストを完全にコーディングする時間がありません =(

(こちら/proc/[pid]/statセクションを見て、stat ファイルがどのようにフォーマットされているかを確認してください)

  while((dirEntry = readdir("/proc")) != NULL) 
  {

      // is a number? (pid)
      if (scanf(dirEntry->d_name, "%d", &dummy) == 1) 
      {
          // get info about the node (file or folder)
          lstat(dirEntry->d_name, &buf);

          // it must be a folder
          if (buf.st_mode != S_IFDIR)
              continue;

          // check if it's owned by the uid you need
          if (buf.st_uid != my_userid)
              continue;

          // ok i got a pid of a process owned by my user
          printf("My user own process with pid %d\n", dirEntry->d_name);

          // build full path of stat file (full of useful infos)
          sprintf(stat_path, "/proc/%s/stat", dirEntry->d_name;

          // self explaining function (you have to write it) to extract the parent pid
          parentpid = extract_the_fourth_field(stat_path);

          // printout the parent pid
          printf("parent pid: %d\n", parentpid);

          // check for the above linked manual page about stat file to get more infos
          // about the current pid
      }
  }
于 2013-01-28T13:00:07.703 に答える