我的任务是编写一个程序,该程序在收到 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/