0

I've been puzzling over this for a while, and now I could use some help. I'm trying to create a loop which will fork off a child process and call "echo hello" through execve().

#include <stdio.h>  
#include <stdlib.h>
#include <sys/wait.h>

int main(int argc, char *argv[],char *envp[]){

  int i = 0;

  while(i<10){ 
    pid_t pid;
    pid = fork();

    if(pid != 0){
      int status;
      waitpid(-1, &status, 0);
    }

    if(pid == 0) {
      char *arg_array[2];
      arg_array[0]="echo";
      arg_array[1]="hello";
      char filename[] = "/bin/echo";     
      if (execve(filename,arg_array,envp) == (-1)) {
        printf("ERROR!\n");
        exit(1);
      }
    }  
    i++;
  }
}

At first the code failed on its first run through, while succeeding on every subsequent run. Now, after cleaning it up for presenting here, it won't succeed at all- all I get is ERROR! x 10. I must have broken something further, and I'm not able to tell what.

This is only my second question on this site, so if you've got any suggestions for improving my questions/ constructive criticism, please share! Thank you.

Hal
  • 37
  • 4

1 Answers1

0

You are missing the final NULL element of the argv array. Using a perror after the execve would also give you the proper error message. Thus:

char *arg_array[3]; arg_array[0] = "echo"; arg_array[1] = "hello"; arg_array[2] = NULL;

Additionally, you are missing #include <unistd.h>

Mark Nunberg
  • 3,551
  • 15
  • 18
  • Hah! That solved it! Wonderful. What does unistd.h do though? It seems to work fine without it. – Hal Oct 19 '14 at 16:57
  • It's always useful to read the documentation for the given function and see which standard header declares it. On my system I got warnings about implicit declarations. Perhaps on your system `` will automatically include ``, but that may not always be the case. – Mark Nunberg Oct 19 '14 at 16:58
  • Thank you, I see now. I'm still a beginner, so although I looked at the documentation, I wasn't quite able to grasp what `` did. – Hal Oct 19 '14 at 17:05