【问题标题】:running a program with wildcards as arguments运行带有通配符作为参数的程序
【发布时间】:2018-05-13 03:55:55
【问题描述】:

所以我有以下代码:

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

【问题讨论】:

  • 我的手册页显示“如果成功,此函数不会返回调用进程。”
  • 你想要的是 fork&exec 一个子进程来执行指定的工作,你的父进程应该等待子进程完成,并且随着每个子进程完成,开始下一个(或者你可以一次启动多个孩子)。

标签: c command-line-arguments


【解决方案1】:

我只列出了第一个:? 那是因为你没有正确理解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()family函数的手册页

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 */

【讨论】:

    【解决方案2】:

    试试这个!

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

    【讨论】:

    • “你什么都不知道,琼恩·雪诺。” (那是C++代码,但是这个问题被标记为C。另外,它与没有足够的参数无关;这是对execl函数的误解。)
    • @ChronoKitsune "冬天来了" :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 2022-11-01
    • 2012-02-17
    • 2019-09-09
    相关资源
    最近更新 更多