Thread: Dup2() help

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    44

    Solved Dup2() help

    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.
    Last edited by TIMBERings; 02-12-2010 at 02:20 PM. Reason: Solved

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 06-02-2009, 06:13 PM
  2. Trying to understand fork, dup2, and execvp
    By Unclejunebug in forum C Programming
    Replies: 0
    Last Post: 04-29-2009, 07:04 PM
  3. dup2 prob
    By WDT in forum C Programming
    Replies: 6
    Last Post: 04-03-2005, 03:42 PM
  4. problem using dup2()
    By talal*c in forum Linux Programming
    Replies: 0
    Last Post: 04-11-2003, 09:44 PM

Tags for this Thread