execve() with redirected stdin from file

Viewed 4998

Want to redirect stdin to file in execve(). So the program should be executed like this, I mean this is how I execute it in shell and it works:

/opt/prog < in.txt

Below is the code I wrote, but it doesn't seem to work. in.txt is binary file, I want to redirect it to stdin in executed program.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main(void)
{
    int fd[2];
    pid_t pid;


    FILE *f = fopen("in.txt", "rb");

    if (pipe(fd) < 0)
        return EXIT_FAILURE;

    if ((pid = fork()) < 0)
        return EXIT_FAILURE;
    else if (pid != 0) { /* father */
        close(fd[1]);
        dup2(fd[0], STDIN_FILENO);
        execlp("/opt/prog", "prog", (char *)0);
        printf("done\n");
    } else { /* son */

        fseek(f, 0, SEEK_END);
        long fsize = ftell(f);
        fseek(f, 0, SEEK_SET);

        char *string = malloc(fsize + 1);
        fread(string, fsize, 1, f);
        fclose(f);
        close(fd[0]);
        write(fd[1], string, 11);
    }

    return EXIT_SUCCESS;
}

Update 1:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main(void)
{
    int fd[2];
    pid_t pid;

    FILE *f = fopen("in.txt", "rb");

    if (pipe(fd) < 0)
        return EXIT_FAILURE;

    if ((pid = fork()) < 0)
        return EXIT_FAILURE;
    else if (pid != 0) { /* father */
        fseek(f, 0, SEEK_END);
        long fsize = ftell(f);
        fseek(f, 0, SEEK_SET);

        char *string = malloc(fsize + 1);
        fread(string, fsize, 1, f);
        fclose(f);
        close(fd[0]);
        write(fd[1], string, 11);

    } else { /* son */
        close(fd[1]);
        dup2(fd[0], STDIN_FILENO);
        execlp("/opt/prog", "prog", (char *)0);
        printf("done\n");

    }

    return EXIT_SUCCESS;
}
2 Answers
Related