LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Redirecting Input and Output in C/C++ (https://www.linuxquestions.org/questions/programming-9/redirecting-input-and-output-in-c-c-759162/)

sklitzz 10-02-2009 04:22 AM

Redirecting Input and Output in C/C++
 
Hi,

I need to run a program that runs under certain limitations( like
memory and execution time) and also I need to redirect its input and
output streams

I have this code below which limits time and memmory but I dont know
how to fit in the redirection. I know you can use "<" and ">" operators
in shell but how do I do it in C/C++?
Code:

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

int main(int argc, char *argv[])
{
    struct rlimit lim;
    int status;

    if ( argc < 4 ) {
    fprintf(stderr, "Usage: %s <time> <memory> <exe>\n",
        argv[0]);
    exit(EXIT_FAILURE);
    }

    if (fork() == 0) {
    lim.rlim_cur = lim.rlim_max = atoi(argv[1]);
    setrlimit(RLIMIT_CPU, &lim);

    lim.rlim_cur = lim.rlim_max = atoi(argv[2]) * 1024 * 1024;
    setrlimit(RLIMIT_AS, &lim);

    if (execl(argv[3], NULL) == -1)
        fprintf(stderr, "I can't run the program.\n");
    } else {
    wait(&status);

    if (WIFEXITED(status))
                fprintf(stderr, "Program enden successfully with exit code: %d\n",
          WEXITSTATUS(status));
    else if (WIFSIGNALED(status))
                fprintf(stderr, "Program ended with signal #%d\n",
            WTERMSIG(status));
    }

    return EXIT_SUCCESS;
}


TIA,
sklitzz

Hko 10-02-2009 04:34 AM

Yes. That is not as easy as it first looks.

You will need to connect a pipe (see: man 2 pipe).

Or run the program with popen() (see: man 3 popen) which is easier but may not fit the code you posted very well.

Here you can read about pipes in C (PDF: look for paragraph 5.4): http://www.advancedlinuxprogramming....p-ch05-ipc.pdf

yeye_olive 10-02-2009 06:17 AM

Where exactly do you want to redirect the input and output to? You might find the dup2() system call useful (see man dup2). It allows you to redefine what a file descriptor refers to. In you example you might want to:

1. open file descriptors to e.g. the files you want the i/o of the child redirected to,
2. then use them to overwrite STDIN_FILENO, STDOUT_FILENO and STDERR_FILENO with dup2(),
3. close the file descriptors opened in 1 as they are useless now,
4. and finally call execl().

carbonfiber 10-02-2009 06:18 AM

Does freopen() not do what you want?

i.e.:

Code:

freopen("carbonfiber.out", "w+", stdout);
freopen("carbonfiber.err", "w+", stderr);



All times are GMT -5. The time now is 09:40 PM.