【发布时间】:2019-04-23 11:52:00
【问题描述】:
我一直在研究以下代码很长一段时间,但无法真正弄清楚。 任务是读取终端命令并每隔 x 秒运行一次;如果命令在等待时间内没有完成,我们想杀死进程,然后再次运行命令。 任何帮助将非常感激。 我很确定我没有正确使用 waitpid();我将如何使用 waitpid 来实现目标?
此外,我将如何检测子进程中的错误?如果子进程发生错误,计划是终止父进程。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
/*
*
*/
int main(int argc, char** argv) {
int waitingTime;
if (argc < 3) {
printf("Invalid number of arguments provided. Please specify a command and exactly one parameter.");
return (EXIT_FAILURE);
}
// -n parameter specified? If so, set the waiting time.
if (argc == 5 && strcmp(argv[3], "-n") == 0) {
waitingTime = atoi(argv[4]);
} else {
waitingTime = 5; // Default waiting time.
}
char* cmd = (char*)malloc(sizeof(argv[1]));
cmd = argv[1];
char* param = (char*)malloc(sizeof(argv[2]));
param = argv[2];
// Print the read command and its param
printf("Command: %s, Parameter: %s, Interval: %d\n\n", cmd, param, waitingTime);
pid_t pid;
for (;;) {
// Declared here for scope
int secsWaited;
secsWaited = 0;
pid = fork();
if (pid == 0) {
pid = getpid();
printf("==============\n");
execlp(cmd, cmd, param, "/", (char *)NULL);
printf("Excec failed; killing the proccess.");
kill(pid, SIGKILL);
} else if (pid > 0) {
int status, code;
for (;;) {
code = waitpid(pid, &status, WNOHANG);
if (code == 0 && secsWaited >= waitingTime) {
kill(pid, SIGKILL);
printf("Child stopped");
break;
} else if (code == 0 && secsWaited < waitingTime) {
secsWaited++;
sleep(1);
} else {
break;
}
}
/*if (!WIFEXITED(status)) {
printf("Time exceeding, stopping child.");
// Get parent process id and kill it.
kill(getpid(), SIGKILL);
}*/
// Sleep for the specified time
sleep(waitingTime - secsWaited);
} else {
return (EXIT_FAILURE);
}
}
free(cmd);
free(param);
return (EXIT_SUCCESS);
}
【问题讨论】:
-
您为此使用 C 的任何特殊原因?这样的任务将更适合 shell 编程或更高级别的编程语言,如 python。
-
我被要求用 C 语言来做,这不是我的主意。
标签: c kill-process waitpid