运行 以通配符作为参数的程序

running a program with wildcards as arguments

所以我有以下代码:

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循环条件有什么问题吗?

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

您应该在每个子进程中使用 fork() & 运行 execl() 创建子进程。也可以使用 argc.

而不是 argv[a] != NULL

示例代码

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() 系列函数的手册页

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.

所以你在 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 */

试试看!

#include <iostream>

int main(int argc, char** argv) 
{
    std::cout << "Have " << argc << " arguments:" << std::endl;

    for (int i = 0; i < argc; ++i)
    {
        std::cout << argv[i] << std::endl;
    }
}