program.exe
program.exe

Reputation: 432

fork process always returning > 0 i cannot figure out why?

Hello i am creating a simple shell in C, currently i am having an issue with fork as it always seems to return a value > 0 even when i type in some non linux command like "ehshhduh" it will still print out"Chile process complete" instead of returning an Error message could anyone explain to me what i am doing wrong thanks?

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h> 
#include <string.h>
#include <unistd.h>
#include <sys/types.h>


char str_tokens[50];

char * get_input() {
    pid_t pid; 
    char *tokens[30][50];
    char input[512];
    char *charp;
    char *burner[20];
  
    int i = 0;

while(true) {
   printf(">");
   if(fgets(input, 512, stdin) == 0 || strncmp(input, "exit", 4) == 0) {    /* reads in input from user no more than 512 chars including null terminator, program terminates if "exit" or CTRL-D is detected*/
     printf("exitting program");
       exit(0);
   } 

    const char delimiters[9] = {'&', ';', '\n', '|', ' ', '\t', '>', '<',}; 
    charp = strtok(input, delimiters); /* splits the string on delimiters */
    while (charp != NULL) {
      
         strcpy(str_tokens, charp);
        charp = strtok(NULL, delimiters);   // sets the char pointer to null
                                                //after each split of the string 
                                                //so the loop eventually terminates */
        } 
       char *args[] = {str_tokens, 0};  

    pid = fork();     // fork a child process
    if (pid == -1) { /* error occured */
        fprintf(stderr, "Error occured with Fork");
        return 1;
    }
     else if (pid > 0) {  /* parent process */
        /* parent will wait for the child process to complete */
        wait(NULL);
        printf("Child process completed") ;
    }
    else if(pid == 0){ // (pid == 0)  /* this is the child process */
        execvp(args[0], args);          /* first param the file path, seconf is null terminated array of char pointers*/
        printf("this is the child process");
        _exit(EXIT_FAILURE);            /* in the case our exec never returns exit */
    }
   

    }
  
   return str_tokens;
}


void run_external(char* commands[50]) {
    commands = get_input();
}

int main () {
 run_external(get_input());
   return(0);
    
}

Upvotes: 0

Views: 344

Answers (1)

dbush
dbush

Reputation: 223739

The call to fork happens before you call execvp on the new program.

First you create a new process, then when you've done that successfully you attempt to start a new program in that process. If the program name is invalid then execvp returns and you _exit the child process.

Also, you should call perror when fork or execvp fail. That will print an error message describing why.

Upvotes: 1

Related Questions