I'm having issues with dup2(). I can write to a file, however it's classified as no read, no write. I want it to be read-only.
I think I have what I need in this excerpt.
graph[i] is an array holding structs
graph[i].prog is a string of OS commands ie ls, echo.
graph[i].output is the file to write to.
Code:
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#define CREATE_FLAGS (O_RDWR | O_CREAT | O_APPEND)
int fileOut=open(graph[i].output, CREATE_FLAGS);
if(fileOut==-1) {
perror("Failed to open file");
return 1;
}
if(dup2(fileOut, STDOUT_FILENO)==-1) {
perror("Failed to redirect standard output");
return 1;
}
pid_t childpid;
childpid=fork();
//Fail to fork
if (childpid==-1) {
perror("Failed to fork");
return 1;
}
//Entered Child
if (childpid==0) {
int numArgs;
char **args;
numArgs=makeargv(graph[i].prog," ", &args);
execvp(args[0],args);
// fileOut=close(*graph[i].output);
perror("Child failed to exec\n");
return 1;
}
Any help would be appreciated, thank you.