为什么setitimer和dup2在execvp之后为子进程工作?

时间:2014-07-22 10:37:02

标签: c dup2 setitimer

首先让我说这里有很多问题。

我的论文的任务之一要求我编写一个执行子程序的程序,如果它的运行时间(不是壁挂时间,但是用户+系统)超过一个特定的值或者它就会杀死它。 RAM消耗量大于另一个指定值。

虽然我还没有想出RAM部分。用setitmer和ITIMER_PROF信号杀死的时间。 (因为ITIMER_PROF收集实际的CPU使用情况,而不是设置一个起始点,然后计算x个时间量)

我使用setitimer的原因是因为我需要的精度低于第二精度。 (E.G.在1.75秒后杀死该过程( 1750000 微秒).setrlimit方法只有第二个。

问题1 为什么不会使用ITIME_PROF的setitimer在父流程中设置?没有收集孩子的CPU /系统调用?

childPID = fork();

if (childPID == -1){
        printf( "Puff paff ... fork() did not work !\n" );
        exit(1);
}

// Child 
if(childPID == 0) {
    execvp(args[0], args);
    exit(1);
}
// Parent
else{
    // Using a ITIMER_PROF inside the parent program will not work!
    // The child may take 1 hour to execute and the parent will wait it out!
    // To fix this we need to use a ITIMER_REAL ( wall-time ) but that's not an accurate measurement 
    struct itimerval timer;
    timer.it_value.tv_sec = 0;
    timer.it_value.tv_usec = 500000;
    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_usec = 500000;
    setitimer ( ITIMER_PROF, &timer, NULL);

    int status;
    waitpid(childPID,&status,0);
    if (WIFEXITED(status)) {
        fprintf(stderr, "Nice nice, the child exited ... with cPID = %d with status = %d \n", cPID, WEXITSTATUS(status) );
    }
}

问题2 为什么这样做?! execvp不会覆盖所有函数(timeout_sigprof,main和其他任何函数)吗?难道有人可能会抓住儿童计划中的信号并取代原来的功能吗?

void timeout_sigprof( int signum ){
    fprintf(stderr, "The alarm SIGPROF is here !\nThe actual pid: %d\n", getpid());
    //TODO: Write output and say the child terminated with
    // ram or time limit exceeded
    exit(105); // Note the 105 !
}

childPID = fork();

if (childPID == -1){
        printf( "Puff paff ... fork() did not work !\n" );
        exit(1);
}

// Child 
if(childPID == 0) {
    // 
    struct sigaction sa;
    memset (&sa, 0, sizeof (sa));
    sa.sa_handler = &timeout_sigprof;
    sigaction (SIGPROF, &sa, NULL);

    struct itimerval timer;
    timer.it_value.tv_sec = 0;
    timer.it_value.tv_usec = 250000;
    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_usec = 250000;
    setitimer ( ITIMER_PROF, &timer, NULL);

    execvp(args[0], args);
    exit(1);
}
// Parent process
else {
    // Waiting for the child
    int status;
    waitpid(childPID,&status,0);
    if (WIFEXITED(status)) {
        fprintf(stderr, "Nice nice, the child exited ... with cPID = %d with status = %d \n", cPID, WEXITSTATUS(status) );
    }
    exit(0);
}

问题3 为什么放在这里的dup2确实有用,让孩子的输入/输出重定向?

childPID = fork();

if (childPID == -1){
        printf( "Puff paff ... fork() did not work !\n" );
        exit(1);
}

// Child 
if(childPID == 0) {

    // Redirect all I/O to/from a file
    int outFileId = open("output", O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);

    // Redirect the output for the CHILD program. Still don't know why it works.
    dup2(outFileId, 1)

    // No idea why these dup2's work ! As i close the file descriptors here ?!
    close(outFileId);

    execvp(args[0], args);
    exit(1);
}
// Parent process
else {
    // Waiting for the child
    int status;
    waitpid(childPID,&status,0);
    if (WIFEXITED(status)) {
        fprintf(stderr, "Nice nice, the child exited ... with cPID = %d with status = %d \n", cPID, WEXITSTATUS(status) );
    }
    exit(0);
}

这是我编写的代码,只有在X时间(x = 500ms)之后运行才会杀死程序。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/time.h>

volatile pid_t childPID;

// This function should exist only in the parent! The child show not have it after a exec* acording to :
// The  exec()  family  of  functions  replaces  the current process image with a new process image.
void timeout_sigprof( int signum ){
    fprintf(stderr, "The alarm SIGPROF is here !\nThe actual pid: %d\n", getpid());
    //TODO: Write output and say the child terminated with a ram or time limit exceeded
    exit(105); // Note the 105 !
}

int main(int argc, char *argv[]) {
    int cstatus;
    pid_t cPID;

    char *args[2];
    args[0] = "/home/ddanailov/Projects/thesis/programs/prime/prime";
    args[1] = NULL; // Indicates the end of arguments.

    // Handle the SIGPROF signal in the function time_handler in both the child and 
    struct sigaction sa;
    memset (&sa, 0, sizeof (sa));
    sa.sa_handler = &timeout_sigprof;
    sigaction (SIGPROF, &sa, NULL);

    childPID = fork();

    if (childPID == -1){
            printf( "Puff paff ... fork() did not work !\n" );
            exit(1);
    }

    // Child 
    if(childPID == 0) {
        struct itimerval timer;
        timer.it_value.tv_sec = 0;
        timer.it_value.tv_usec = 250000;
        timer.it_interval.tv_sec = 0;
        timer.it_interval.tv_usec = 250000;
        setitimer ( ITIMER_PROF, &timer, NULL);

        // Redirect all I/O to/from a file
        int outFileId = open("output", O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
        // int inFileId = open("input");

        // Redirect the output for the CHILD program. Still don't know why it works.
        //dup2(inFileId, 0);
        dup2(outFileId, 1);
        //dup2(outFileId, 2);

        // No idea why these dup2's work ! As i close the file descriptors here ?!
        close(outFileId);
        close(inFileId);

        execvp(args[0], args);
        exit(1);
    }
    // Parent process
    else {
        // Waiting for the child
        int status;
        waitpid(childPID,&status,0);
        if (WIFEXITED(status)) {
            fprintf(stderr, "Nice nice, the child exited ... with cPID = %d with status = %d \n", cPID, WEXITSTATUS(status) );
        }
        exit(0);
    }

    return 0;
}

非常感谢任何帮助/解释!

提前谢谢大家,

实施例

1 个答案:

答案 0 :(得分:2)

问题1

  

为什么带有ITIME_PROF的setitimer不能正常工作   在父进程中设置?孩子的CPU /系统调用是   不是被它收集的?

不,他们不是。与ITIME_PROF相关的定时器仅在具有定时器设置的进程正在执行时,或者系统调用正在代表它执行时递减,而不是在子进程正在执行时递减。

这些信号通常由分析工具使用,该分析工具包含在链接到您要分析的程序的库中。

但是:您可能无需将信号发送到父进程。如果你的目标是在超过允许的使用量时终止程序,那么让它接收SIGPROF并退出(如下面我对Q2的回答所示)。然后,在waitpid返回并且您检测到程序因SIGPROF而退出后,您可以通过调用timesgetrusage来查找该孩子使用的实际时间。

唯一的缺点是子程序可以通过在SIGPROF上设置它自己的信号处理程序来破坏这个过程。

问题2

  

为什么这个工作!? execvp不会覆盖所有的   函数(timeout_sigprof,main和其他)?而且不可能有人   潜在地抓住儿童计划中的信号并取代   原来的功能?

它没有,或者至少不是你的想法。正如您所说,您在父进程中安装的信号处理程序将被execvp加载的新映像替换。

它似乎工作的原因是如果新程序没有为SIGPROF设置信号处理程序,那么当该信号被发送到进程时它将终止。回想一下,发送给进程的任何信号都没有为该进程设置处理程序,或者特别决定忽略,这将导致进程终止。

如果execvp 正在执行的程序为SIGPROF设置信号处理程序,那么它将不会被终止。

<强>更新

看到你的评论后,我想我最好试试你的程序。我在waitpid之后向if语句添加了另一个分支,如下所示:

    waitpid(childPID,&status,0);
    if (WIFEXITED(status)) {
        fprintf(stderr, "Nice nice, the child exited ... with cPID = %d with status = %d \n", childPID, WEXITSTATUS(status) );
    } else if (WIFSIGNALED(status)) {
        fprintf(stderr, "Process pid=%d received signal %d\n",childPID,WTERMSIG(status));
    }

当我运行时,我看到以下内容:

$ ./watcher
Process pid=1045 received signal 27

这验证了我上面所说的内容。我没有看到字符串“警报SIGPROF在这里!”打印出来,我确实在父母看到孩子被信号27杀死了,这是信号。

我只能想到一种情况,在这种情况下你会看到信号处理程序执行,如果计时器设置得太低,它会在execv实际设法加载新图像之前触发。但这看起来并不完全可能。

另一种可能性是您无意中在目标程序中安装了相同的信号处理程序(复制粘贴错误?)。

问题3

  

为什么放在这里的dup2实际上是有用的,让我们来吧   要重定向的孩子的输入/输出?

我从代码中的注释中假设你的意思是“即使我在dup2之后立即关闭原始文件描述符,它仍然有效吗?”

dup2将旧FD复制到新FD中,因此执行后:

dup2(outFileId, 1);

你有两个引用相同文件描述的文件描述符:变量outFileId中包含的文件描述符和FD 1(stdout)。另请注意,此操作将关闭原始标准输出。

文件描述符类似于对基础文件描述数据结构的引用,该结构表示打开的文件。在调用dup2之后,有两个文件描述符指向相同的文件描述。

close的手册页说:

  

如果fd是引用底层open的最后一个文件描述符   文件描述(参见open(2)),与open相关的资源   文件描述被释放

所以它正常工作:你仍然有一个FD打开,FD 1(stdout),新的子进程可以写入它。