Thread: double fork for implement background

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    3

    double fork for implement background

    Hi!
    I've been tring to do backgrounding by having the first child process fork and then immediately exit, with the grandchild executing the requested program.

    But I don't know why I keep getting two copies of output

    my code for implementing background:
    Code:
    if(cmd->background == 1){
        pid_t childPid;
    
       
        
        if((childPid == fork()) < 0){  /* error */
          perror("BAD FORK");
    
        }else if(childPid == 0){ /* child process */
         
          exit(0);
        }
        else if((childPid = fork()) == 0){ /*grandchild process */
    
          execvp(cmd->argvs[0][0], cmd->argvs[0]);
    	
        }else{ /* parent process */
    
          waitpid(childPid, NULL, WNOHANG);
          
        }
    Then I ran the command like this "seq 1 5", the result I get was:
    Code:
    shell: seq 1 5 &
    shell: shell: 1
    2
    3
    4
    5
    1
    2
    3
    4
    5
    Can anyone tell me what's wrong with my code?
    Last edited by yen; 11-25-2010 at 12:25 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    34,940
    It isn't a series of if / else if
    Code:
    if ( fork() == 0 ) {
      if ( fork() == 0 ) {
        // grandchild
      } else {
        // child
      }
    } else {
      // parent
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    3
    oh yeah! How blind I am!

    Thank you so much Salem!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Double
    By trillykins in forum C Programming
    Replies: 7
    Last Post: 11-25-2010, 01:38 AM
  2. Help me please.
    By yann in forum C Programming
    Replies: 15
    Last Post: 09-29-2009, 10:04 PM
  3. Conversion From C++ To C
    By dicon in forum C++ Programming
    Replies: 2
    Last Post: 06-10-2007, 03:54 PM
  4. functions and passing data
    By redmondtab in forum C Programming
    Replies: 41
    Last Post: 09-21-2006, 01:04 PM
  5. Please HELP!!
    By traz in forum C++ Programming
    Replies: 4
    Last Post: 04-14-2003, 10:20 PM
Website Security Test