首页 > 解决方案 > 运行带有通配符作为参数的程序

问题描述

所以我有以下代码:

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;
}   

我想列出三个名为tickets1.lot、tickets2.lot、tickets3.lot 的文件。但是当我以这种方式运行程序时:

./code ../input/ .lot*

我只列出了第一个:

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

../input/tickets1.lot

我的 while 循环条件有什么问题吗?

标签: ccommand-line-arguments

解决方案


我只列出了第一个:?那是因为你没有execl()正确理解。第一次用新进程execl()替换当前进程(a.out)并完成,循环不会再次迭代,因为没有进程在运行。

您应该使用fork()&execl()在每个子进程中运行来创建子进程。也代替 argv[a] != NULL使用argc.

示例代码

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;
}

来自execl()家庭功能的手册页

exec() 系列函数用新的进程映像替换当前进程映像。并且 exec() 函数仅在发生错误时返回。

execl()因此,只有在发生错误时才会执行调用后所做的任何事情。例如

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 bcz above statement replaces a.out process with new process called ls */

推荐阅读