我正在尝试使用内置命令创建一个基本shell,我遇到了一些getopt问题。这是输出(使用valgrind):
$ mkdir -p foo/bar
mkdir
-p
foo/bar
FLAGON
$ mkdir -p foo/test
mkdir
-p
foo/test
==15377== Invalid read of size 1
==15377== at 0x5201BBE: _getopt_internal_r (in /usr/lib/libc-2.17.so)
==15377== by 0x5202CEA: _getopt_internal (in /usr/lib/libc-2.17.so)
==15377== by 0x5202D37: getopt (in /usr/lib/libc-2.17.so)
==15377== by 0x40351A: shell_ns_cmd_mkdir (shell.c:542)
==15377== by 0x403AB4: normal_shell_cb (shell.c:610)
==15377== by 0x402E8E: shell_mainloop (shell.c:402)
==15377== by 0x401B67: main (main.c:52)
==15377== Address 0x54e0912 is 2 bytes inside a block of size 3 free'd
==15377== at 0x4C2AD3C: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==15377== by 0x402C93: shell_mainloop (shell.c:384)
==15377== by 0x401B67: main (main.c:52)
==15377==
$
这是源(剪辑):
for (i = 0; i < argc; i++) {
puts(argv[i]);
}
while ((c = getopt(argc, argv, "p")) != -1) {
switch (c) {
case 'p':
puts("FLAGON");
mkparents = true;
break;
case '?':
fprintf(stderr, "invalid option -- %c", optopt);
ret = 127;
goto end;
break;
}
}
因此,第一次运行它(mkdir -p
)识别它(-p
),第二次运行时,它不会。有什么想法吗?
答案 0 :(得分:16)
如果您要扫描多个向量,则需要将getopt
设置为1来重置optind
。
变量optind是argv []的下一个元素的索引 矢量要处理。 系统应将其初始化为1 , 和getopt()将在它的每个元素完成时更新它 的argv []。
如果将optind
设置为1不起作用,请尝试0
,我想我记得在某处阅读过。