Hi,

I'm trying to make this code works but with no luck so far, I have two problems
1. I'm reading from a file lines and then executing them but the last line goes into an infinite loop
2. Another problem is I don't think I'm using "wait" properly as it giving some random junk after the first line is executed.

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

#define COMM_LEN 128
#define MAX_ARGS 100

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

    char Command[COMM_LEN];
    int pid, status;
    char *Command_AR[MAX_ARGS];
    int counter;
    FILE *fp;

    if(argc!=2)
      {
          perror("Invalid command");
          exit(0);
      }

     if((fp=fopen(argv[1],"r"))==NULL)
      {
          perror("Error Opening File");  
      }


    fgets(Command,COMM_LEN,fp);
    Command[strlen(Command)-1] = '\0';
    while (strcmp(Command,"\0")) {
        if ((pid = fork()) == -1) {
            perror("fork");
            exit(-1);
        }
        if (pid == 0) {
            counter = 0;
            Command_AR[counter] = strtok(Command," ");
            while (Command_AR[counter++] != NULL) {
                Command_AR[counter] = strtok(NULL," ");
            }
            execvp(Command_AR[0],Command_AR);
            perror("exec");
            exit(-1);
        }

         else {
              fgets(Command,COMM_LEN,fp);
              Command[strlen(Command)-1] = '\0';
             }
           while(wait(&status)!=pid)
         {
           /*do nothing*/;
         }
      }
    return(0);
}

Recommended Answers

All 2 Replies

while (strcmp(Command,"\0" )) When would ever occur that a string is made of string[0] = '\0'; and string[1] = '\0';? That's what "\0" is; a string of 2 bytes.

Strcmp:          if:
Returns value    Explanation
-------------    -----------
less than 0     str1 is less than str2
equal to 0      str1 is equal to str2
greater than 0  str1 is greater than str2

Since the result of strcmp(Command, "\0") will never be 0 or ( strings are the same ); we must conclude that it will always be less or greater than 0 value, allowing while to loop forever.

Thank you for your reply,

I tried changing it to '\0' but it's giving me a bus error, how can it be fixed? I'm trying to make the program stop once it has read and executed the line in the file

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.