c - 运行带有通配符作为参数的程序
问题描述
所以我有以下代码:
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()
在每个子进程中运行来创建子进程。也代替 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 */
推荐阅读
- reactjs - vs code 自动重命名标签颜色管理
- c# - 如何将变量用于开关案例的“案例”
- r - 更改数据格式
- android - 发布到 FB 页面墙时 FB Graph API OAuth 403 错误
- reactjs - 如何重新使用反应回调来提升状态?
- java - 如何使用 Log4J 在一行中打印日志语句?
- nutch - 在 Nutch1.16 上获取没有 URLs to Fetch 错误
- javascript - 如何让微软的cognitive-services-speech-sdk-js手动停止收听?
- debugging - 跨平台:使用 Visual Studio 2019 使用共享动态库时在 Windows 下使用 WSL 进行调试失败
- c# - 允许匿名查看剃须刀页面,但授权发布