Search code examples
ccommand-line-arguments

running a program with wildcards as arguments


So I have the below code:

int main(int argc, char *argv[])
{
    int a=1;

    while(argv[a] != NULL)
    {
    printf("\nargv[a] = %s\n", argv[a]); 
    execl("/bin/ls", "ls", argv[a], NULL);
    a++;
    }
    return 0;
}   

I want to list three files called tickets1.lot, tickets2.lot, tickets3.lot. But when I run the program this way:

./code ../input/.lot*

I only get the first one listed:

argv[a] = ../input/tickets1.lot

../input/tickets1.lot

Is there anything wrong in my while loop condition?


Solution

  • I only get the first one listed: ? That's because you didn't understand execl() correctly. The very first time execl() replaces the current process(a.out) with a new process, the loop will not iterate again as there is no process running.

    You should create the child process using fork() and call execl() in each child process. Also instead of argv[a] != NULL use argc.

    Sample code:

    int main(int argc, char *argv[]) {
            int a = 0;
            while(++a < argc) { /* check this condition, how many process are there, that many times  it should iterate */
                    printf("\nargv[a] = %s\n", argv[a]); 
                    if(fork()) { /*every time parent process PCB replaced by /bin/ls process */
                            execl("/bin/ls", "ls", argv[a], NULL);
                            //a++; /*this will not execute */
                    }
                    else
                            ;
            }
            return 0;
    }
    

    From the manual page of execl() family function:

    The exec() family of functions replaces the current process image with a new process image.

    And:

    The exec() functions return only if an error has occurred.

    So what ever you do after the execl() call will execute only if an error has occurred. For example:

    execl("/bin/ls", "ls", NULL); /* ls is the new process, old process is a.out if you are not creating process using fork() */ 
    a++; /* this will not execute because above statement replaces a.out process with new process called ls */