C 超过时间限制时终止进程

C 超过时间限制时终止进程,c,kill-process,waitpid,C,Kill Process,Waitpid,我已经为下面的代码工作了相当长的时间,但是我不能真正理解它。 任务是读取终端命令并每x秒运行一次;如果命令没有在等待时间内完成,我们希望终止进程,然后再次运行该命令。 任何帮助都将不胜感激。 我很确定我没有正确使用waitpid();我将如何使用waitpid来实现目标 此外,我将如何检测子进程中的错误?计划是在子进程中发生错误时终止父进程 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #

我已经为下面的代码工作了相当长的时间,但是我不能真正理解它。 任务是读取终端命令并每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);
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
/*
* 
*/
int main(int argc,字符**argv){
国际等待时间;
如果(argc<3){
printf(“提供的参数数量无效。请指定一个命令和一个参数。”);
返回(退出失败);
} 
//指定了-n参数?如果是,请设置等待时间。
如果(argc==5&&strcmp(argv[3],“-n”)==0){
waitingTime=atoi(argv[4]);
}否则{
waitingTime=5;//默认等待时间。
}
char*cmd=(char*)malloc(sizeof(argv[1]);
cmd=argv[1];
char*param=(char*)malloc(sizeof(argv[2]);
param=argv[2];
//打印read命令及其参数
printf(“命令:%s,参数:%s,间隔:%d\n\n”,cmd,param,waitingTime);
pid_t pid;
对于(;){
//在此处声明范围
国际安全委员会;
secsWaited=0;
pid=fork();
如果(pid==0){
pid=getpid();
printf(“=========================\n”);
execlp(cmd,cmd,param,“/”,(char*)NULL);
printf(“EXEC失败;终止进程”);
kill(pid,SIGKILL);
}否则,如果(pid>0){
int状态,代码;
对于(;;){
代码=等待pid(pid和状态,WNOHANG);
如果(代码==0&&secsWaited>=waitingTime){
kill(pid,SIGKILL);
printf(“儿童停止”);
打破
}else if(代码==0&&secsWaited
您的逻辑有点太复杂(例如,有太多不同的
睡眠
调用和
if/else
梯形图逻辑)

另外,不需要
malloc
字符串
argv
它们可以直接使用

我已经对它进行了简化,并对其进行了一些重构,以使其能够正常工作[请原谅这种无缘无故的风格清理]:

#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 = argv[1];
    char *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;
    int code = -1;
    int status;
    int killflg = 1;

    for (;;) {
        // Declared here for scope
        int secsWaited;

        secsWaited = 0;
        pid = fork();

        // stop on fork failure
        if (pid < 0) {
            killflg = 1;
            break;
        }

        // child process
        if (pid == 0) {
            pid = getpid();
            printf("==============\n");
#if 0
            execlp(cmd, cmd, param, "/", (char *) NULL);
#else
            execlp(cmd, cmd, param, (char *) NULL);
#endif
            printf("Excec failed; killing the proccess.");

// NOTE/BUG: this is the child so pid is zero, so killing it is wrong
#if 0
            kill(pid, SIGKILL);
#else
            exit(1);
#endif
        }

        killflg = 0;
        for (;;) {
            code = waitpid(pid, &status, WNOHANG);
            if (code > 0)
                break;

            if (killflg)
                continue;

            secsWaited++;
            sleep(1);

            if (secsWaited >= waitingTime) {
                printf("timeout\n");
                kill(pid, SIGKILL);
                killflg = 1;
            }
        }

        if (! killflg)
            break;
    }

#if 0
    free(cmd);
    free(param);
#endif

    if (killflg)
        code = EXIT_FAILURE;
    else
        code = EXIT_SUCCESS;

    return code;
}

旁注:我在这里使用了
usleep
,但是,尽管稍微复杂一点,但是使用
nanosleep

被认为是更好的选择。您使用C的具体原因是什么?这样的任务更适合于shell编程或更高级别的编程语言,比如python。我被要求用C语言来完成,这不是我的主意。好吧,这很有意义,并帮助我理解相关的命令。然而,我还有一个问题:现在,程序将在一次迭代后停止;如果删除“if(!killflg)”处的断点,它将按预期工作。我是错过了什么,还是这只是一个误会?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <time.h>

double
tvgetf(void)
{
    struct timespec ts;
    double sec;

    clock_gettime(CLOCK_REALTIME,&ts);

    sec = ts.tv_nsec;
    sec /= 1e9;
    sec += ts.tv_sec;

    return sec;
}

/*
 *
 */
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 = argv[1];
    char *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;
    int code = -1;
    int status;
    int killflg = 1;
    double todzero = tvgetf();

    for (;;) {
        // Declared here for scope
        double todbeg = tvgetf();
        double todelap;

        pid = fork();

        // stop on fork failure
        if (pid < 0) {
            killflg = 1;
            break;
        }

        // child process
        if (pid == 0) {
            pid = getpid();
            printf("============== (%.9f)\n",tvgetf() - todzero);
            execlp(cmd, cmd, param, (char *) NULL);
            printf("Excec failed; killing the proccess.");
            exit(1);
        }

        killflg = 0;
        for (;;) {
            code = waitpid(pid, &status, WNOHANG);
            if (code > 0)
                break;

            if (killflg)
                continue;

            usleep(1000);

            todelap = tvgetf() - todbeg;
            if (todelap >= waitingTime) {
                printf("timeout\n");
                kill(pid, SIGKILL);
                killflg = 1;
            }
        }

        // do _not_ wait -- we already timed out
        if (killflg)
            continue;

        // get final elapsed time for this round and the amount of time
        // remaining until the next interval
        todelap = tvgetf() - todbeg;
        useconds_t time_to_wait = ((double) waitingTime - todelap) * 1e6;

        // wait until the next time period
        if (time_to_wait > 0)
            usleep(time_to_wait);
    }

    if (killflg)
        code = EXIT_FAILURE;
    else
        code = EXIT_SUCCESS;

    return code;
}