Question

I'm doing a small c program for testing some Unix commands. I provide the user with choices he can test and then allows him to enter his choice. If the user enters the number 2 as his choice ,the following code should run which is testing the grep command on a file. But there is something wrong with the code when I enter the "pattern", it starts an infinite loop , Any help ?!! I don't have much experience in Unix progamming. the problem appears when I enter the number 2 as my choice ,means that it's in case no.2

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

    int main(){
    char pattern[50];
    int userInput;
    pid_t childPID; 
        char filename[50];   
    FILE *file;      

    printf("Enter a File name:");    
    scanf("%s",filename);    

        file = fopen(filename, "r");


do{
    printf("Enter what u want to do with the file:\n");
    printf("1.Compress the file.\n");
    printf("2.Search for a pattern at the file\n");
    printf("3.Read the file (display the file content at the terminal)\n");
    printf("4.Eject the program\n");

        scanf("%d",&userInput);
switch(userInput){
    case 1: 
        if(childPID == 0){
            execl("/bin/gzip","gzip",filename,NULL);

            exit(1);
            }       
        break;
    case 2: childPID = fork();
        if(childPID ==0){
            printf("Enter the pattern you want to search about:");
            scanf("%s",pattern);


            execl("/bin/grep","grep",pattern,filename,NULL);
        }   
        break;

    }

}while(userInput != 4);
return 0;
  }
Was it helpful?

Solution

The execlp() or exec() family of functions replaces the current process image with a new process image so when execlp() exits then child terminates but fork() returns some non-zero value to parent process.

The main point is after doing fork() there are two independent processes

1st : main process called parent 
2nd : child process

And you can't control their execution order it's unspecified. so put wait(NULL) in you parent code just after the child code finishes.

So that parent will wait till child terminates. otherwise both independent processes will run in this way. Sometimes you find that only parent is running (that's infinite loop) but sometimes you see that child is running too.

OTHER TIPS

The only reason I see this could get into an infinite loop is when execl() fails. Print errno after execl() to see what's going wrong.

...
    execl("/bin/grep","grep",pattern,filename,NULL);
    printf("errno=%d\n", errno);
}

break;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top