如何输出运行时错误'一个程序由execvp函数运行到一个文件?

时间:2015-03-30 15:56:59

标签: c linux fork execvp dup2

我在eclipse,linux上编写程序,我需要将内部程序a.out(由execvp())函数运行的结果输出到文件中(我正在使用execvp函数,但每个其他exec函数都很好。

程序运行正常,输入正确,并输出到我定义的文件中。

问题是我需要输出每个输出,甚至错误(运行时错误,如segFault)消息,这些消息将被输入,这将导致内部程序a.out失败(例如除以零)。

这是我调用execvp的程序的代码:

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


int main() {
    //string for execvp to run "a.out"
    char *arg[] = {"./a.out", NULL};
    //name of input file
    char *input = "input.txt";
    pid_t child_pid;
    int child_status;
    int input_fd, fd_output;
    //open input.txt
    if ((input_fd = open(input, O_RDONLY)) < 0)
    {
        perror("");
        exit(-1);
    }
    //redirect standard input to input.txt
    dup2(input_fd, 0);
    //create output.txt
    if ((fd_output = open("output.txt",
            O_CREAT|O_TRUNC|O_RDWR, 0644)) < 0)
    {
        perror("");
        exit(-1);
    }
    //redirect standard output and standard error to output.txt
    dup2(fd_output, 1);
    dup2(fd_output, 2);

    child_pid = fork();
    if(child_pid == 0) {
        // This is done by the child process.
        execvp(arg[0], arg);

        // If execvp returns, it must have failed.
        perror("fork");
        exit(0);
    } else {
        // This is run by the parent. Wait for the child to terminate.
        if (wait(&child_status) == -1) {
            printf("error!\n");
        }
    }
    return 0;
}

a.out源文件:

#include <stdio.h>
#include <unistd.h>
int main () {
    int op, num1, num2;
    do {
        printf("Please enter operation\r\n");
        scanf("%d", &op);
        switch(op) {
        case 1:
            printf("Please enter two numbers\r\n");
            scanf("%d %d", &num1, &num2);
            printf("The devision is %d\r\n", num1/num2);
            break;
        case 4:
            printf("Bye\r\n");
            break;
        default:
            break;
        }
    }while(op != 4);
    return 0;
}

好`input.txt':

1
3 4
4

坏`input.txt:

1
3 0
4

为了获得良好的输入,我得到output.txt

Please enter operation
Please enter two numbers
The devision is 0
Please enter operation
Bye

但是对于输出错误,我得到一个空白的output.txt文件,无论如何。 那么如何将a.out错误(如果有的话)输出到output.txt?

0 个答案:

没有答案