1

我的任务是编写一个程序,该程序列出所有活动用户,以及当程序接收到 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;
}
4

1 回答 1

2

您需要阅读有关运算符优先级的信息。线

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

不做你认为它做的事!

实际上编译器将其视为

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

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


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

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

于 2013-10-27T15:10:58.693 回答