c - 如何列出所有用户和他们活跃的进程数

标签 c linux

我的任务是编写一个程序,该程序在收到 SIGHUP 信号时列出所有事件用户及其事件的进程数量,并在收到 SIGINT 信号时退出。

我有这个用于列出用户和进程数

ps -u "$(echo $(w -h | cut -d ' ' -f1 | sort -u))" o user= | sort | uniq -c | sort -rn

这就是我的程序。我可能会以错误的方式解决问题,需要一些帮助。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>

void sig_handler(int signo) {
  if (signo == SIGHUP){
    int pid = 0;
    if (pid = fork() != 0) {
      execl("/bin/ps", "ps", "-u", "\"$(echo $(w -h | cut -d ' ' -f1 | sort -u))\"", "o", "user=", "|", "sort", "|",  "uniq", "-c", "|", "sort", "-rn", NULL);
    } else {
      printf("Signal received: SIGINT\nReported by: Parent process\n\n");
    }
  }
}

int main(void) {
  if (signal(SIGHUP, sig_handler) == SIG_ERR)
    printf("\nCan't catch SIGINT\n");

  while (1)
    sleep(1);
  return 0;
}

最佳答案

您需要阅读有关 operator precedence 的内容.线路

if (pid = fork() != 0) {

并不像你想象的那样!

事实上编译器将其视为

if (pid = (fork() != 0)) {

除其他外,这意味着您在父进程中运行 execl,而不是按照惯例在子进程中运行。


至于你的问题,这是因为你试图运行特定于 shell 的东西(嵌入式命令、管道等),但你实际上并没有运行 shell。

要么你必须exec一个shell,要么使用例如system 函数。

关于c - 如何列出所有用户和他们活跃的进程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19619527/

相关文章:

c - MIPS memcpy 问题(我认为)

c - 监听系统调用中的积压值

c# - 从c#中的linux "ps"命令输出解析进程启动时间

c++ - 编译 qt 项目给 operator delete(void*, unsigned int) undefined reference

linux - Scheme 中的二次公式

linux - 使用 sed 为选项卡添加背景颜色?

c++ - pthread_cond_wait() 能否始终赢得锁定互斥体的竞争?

c - 如何将 getchar() 与字符串一起使用?

c - 如何从设备将设备注册到azure iot hub(使用iot客户端c sdk)

ruby-on-rails - rails : running rake task in cron job