所以我有以下代码:
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/