CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Help with file

  1. #1
    Join Date
    Dec 2004
    Posts
    22

    Help with file

    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.
    Code:
    #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);
    }

  2. #2
    Join Date
    Oct 2004
    Posts
    296

    Re: Help with file

    You might want to post that in a C forum.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured