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

标签 c command-line-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) 并完成,循环将不会再次迭代,因为没有进程在运行。

您应该使用 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 */

关于c - 以通配符作为参数运行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50309986/

相关文章:

带有 '<' 和 '- option' 的命令行 C

c++ - 使用 WinAPI 进行夏令时和 UTC 到本地时间的转换

c - 使用字符串和 Malloc/Realoc

c++ - 在具有不同 UDP 端口的联网计算机上发送/接收数据包

c - 使用结构数组从文件读取时出现问题

linux - 如何制作脚本或程序来运行某些命令?

c - 在 C 程序中使用 exit_failure 时出现运行时错误

python - 将元组作为命令行参数传递

macos - 从 Mac 中的 pkg 文件安装后打开应用程序

Java Eclipse 在运行时连续获取命令行参数