0

I'm trying to write, as part of my code, a function so that a user can type

shell> run date     //Line of user input
Mon Jan 19 11:51:57 EST 2009  //Printed by program
shell: process 348 exited normally with status 0

The user just types 'run date' and the program displays the bottom two lines. This is what I have in my function so far..

 else if(strcmp(argv[1],"run") == 0 ) {
           if ((pid = fork()) < 0) {  //Child process fork
                    perror("fork");       
                    exit(1);
                    }   
            //printf("ok");
            if (pid == 0) {  //Child executes code
                    execvp(argv[2], &argv[2]); 
                    exit(1);
                    }

    waitpid(atoi(argv[2]), &status, WNOHANG);

    printf("shell: run status is %d\n", status);
    }

This is not producing that yet, but I wanted to know if this is correct so far and if I'm missing an important part! Thank you.

user3295674
  • 893
  • 5
  • 19
  • 42

1 Answers1

4

The first argument to waitpid should the child's PID. Also, note that the WNOHANG option prevents the calling process from being blocked; as such,waitpid will return 0 if status information for the intended process is not available. If you want to wait until the child has terminated, use 0 as the third argument for waitpid (or use wait instead of waitpid).

  • Alternatively, the first argument being zero waits for any child; this can be useful if commands have been run in the background (it allows the shell to avoid zombies), but you need a loop around the `waitpid()` call. You should probably report on the PID that was returned by `waitpid()` as well as the status. The status is more comprehensible if printed in hex (the low-order byte is normally zero unless the child died from a signal). – Jonathan Leffler Feb 20 '14 at 02:40