c - 是否可以重复getopt

标签 c getopt

我正在尝试使用内置命令创建一个基本的 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) 而第二次运行时,它没有。有什么想法吗?

最佳答案

如果您想扫描多个 vector ,您需要通过将 optind 设置为 1 来重置 getopt

The variable optind is the index of the next element of the argv[] vector to be processed. It shall be initialized to 1 by the system, and getopt() shall update it when it finishes with each element of argv[].

如果将 optind 设置为 1 不起作用,也可以尝试 0,我想我记得在某处读过相关内容。

关于c - 是否可以重复getopt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50222134/

相关文章:

c - strcpy 损坏 char 数组(字符串值)

c++ - 自动更新结构体中的指针值

c - optarg 值是否在对 getopt 的连续调用中保持不变?

c - `-V` 标志如何既是 `--verbose` 又是 `--version` ?

perl - 您是否应该检查 Getopt::Long::GetOptions 的返回码?

python - 获取原始输入作为选项?

perl - 如何使用 Getopt::Std 响应 --help 标志?

c - 写入命名管道未显示字符串的全部内容

c - 使用 packet_mmap 发送任意以太网帧但无法设置环

c - 共享内存不分配?