2
#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>


#define PORT 12344

int main(int argc, char** argv) {
    int opt;
    int server_fd, client_fd, epoll_fd;
    int child_pid;
    int port = PORT;
    char* file = NULL;

    /* Argparse */
    static struct option long_options[] = {
        {"file", required_argument, 0, 'f'},
        {"port", optional_argument, 0, 'p'},
        {"help", no_argument, 0, 'h'},
        {NULL, 0, NULL, 0}
    };


    while ((opt = getopt_long(argc, argv, "f:p:h", long_options, NULL)) != -1) {
        switch (opt) {
            case 'f':
                printf("file is: %s\n", optarg);
                break;
            case 'p':
                port = atoi(optarg);
                // since we will be listening on port > 1024 anyway, 0 is unused
                if (!port) {
                    printf("not a valid port\n");
                    exit(1);
                }
                break;
            case 'h':
                printf("help message\n");
                exit(0);
            default:
                break;
        }
    }

    printf("end\n");
}

I am trying to build an application based on TCP. I want the program to take two arguments, a file parameter which specifies the configuration file, a number which is basically the port number to listen on The oher arguments work just fine. But, whenever I try to use the --port ABC option, the program crashes with a Segmentation fault.

What am I missing here?

14
  • 1
    If you catch the crash in your debugger, does it happen where you expect it to happen? What is the value of opt and optarg at that point? Commented Nov 4, 2024 at 8:58
  • 1
    Oh, and why optional_argument for the port argument? That makes no sense. Commented Nov 4, 2024 at 9:06
  • 3
    For long option format you need to use =. Either -p ABC or --port=ABC. If you use --port ABC you will get optarg == NULL causing your segfault. Commented Nov 4, 2024 at 9:06
  • 1
    And you should handle the '?' that can be returned on invalid options. Commented Nov 4, 2024 at 9:07
  • 1
    @Someprogrammerdude I wasn't able to find any source for this, but that is what I observed by simply testing it using Ubuntu in WSL2. I would also expect it should work with long option without =. Commented Nov 4, 2024 at 9:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.