#include <stdio.h> //for printf
#include <stdlib.h> //for exit
#include <unistd.h>
#include <getopt.h>
void print_help(){
puts("srun [-N nodes] [-n tasks] executable\n\
-N number of nodes\n\
-n number of tasks\n\
-h --help print the help");
}
/*
* no_argument (or 0) if the option does not take an argument;
* required_argument (or 1) if the option requires an argument;
* optional_argument (or 2) if the option takes an optional argument.
*
* struct option {
const char *name;
int has_arg;
int *flag;
int val; //is the value to return, or to load into the variable pointed to by flag.
};
The last element of the array has to be filled with zeroes.
*/
struct option long_options[] = {
{ "nodes", 1, NULL, 'N' },
{ "tasks", 1, NULL, 'n' },
{ "interaction", 2, NULL, 'i' },
{ "help", 0, NULL, 'h' },
{ 0, 0, 0, 0 }
}; //const char *short_options = "N:n:i::h";
/*
#define _GNU_SOURCE
#include <getopt.h>
int getopt_long(int argc, char * const argv[], const char *optstring,
const struct option *longopts, int *longindex);
//longopts is a pointer to the first element of an array of struct option
int getopt_long_only(int argc, char * const argv[], const char *optstring,
const struct option *longopts, int *longindex);
//If longindex is not NULL, it points to a variable which is set to
//the index of the long option relative to longopts.
*/
void get_opt_in_long(int argc, char **argv){
const char *short_options = "N:n:i::h";
int opt;
while((opt = getopt_long(argc, argv, short_options, long_options, NULL)) != -1){
switch(opt){
case 'N':
printf("nodes -N, optarg = %s\n", optarg);
break;
case 'n':
printf("tasks -n, optarg = %s\n", optarg);
break;
case 'i':
if(!optarg)
puts("Nict to meet you!");
else
printf("Nict to meet you! %s\n", optarg);
break;
case 'h':
print_help();
break;
case '?':
printf("can't recognize, the optopt = %c\n", (char)optopt);
break;
default:
break;
}
printf("optind = %d\n", optind);
}
//after scan options, other argv has been moved to the end part of argv[]
if(optind < argc){
for(; optind < argc; optind++)
printf("%s ", argv[optind]);
putchar('\n');
}
}
int main(int argc, char **argv){
get_opt_in_long(argc, argv);
return 0;
}