Please reffer to getopt-优雅地处理命令行参数 | 守望的个人博客 (yanbinghu.com).
There is one mistake in this blog.
It seems that he just used the “-n” option, but forgot to add a parameter.

//one example about sleep and args
//this is my watering program
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pigpio.h>
#include <string.h>
#include <signal.h>
extern int optind, opterr, optopt;
extern char *optarg;
void sig_handler(int num)
{
gpioWrite(18, 0);
printf("Interupted, exiting program...\n");
printf("\nrecvive the signal is %d\n", num);
exit(-1);
}
int main(int argc, char *argv[])
{
int c = 0;
int times = 0;
printf("There are %d args\n", argc);
if (argc != 2 && argc != 3)
{
printf("Wrong args\n");
printf("use -f to water your flower fully\n");
printf("use -d to water your flower in daily water\n");
printf("use -h t to water your flower in t times\n");
exit(0);
}
while (EOF != (c = getopt(argc, argv, "fdh:")))
{
switch (c)
{
case 'f':
printf(":Fully:\n");
times = 30;
break;
case 'd':
printf(":Daily:\n");
times = 3;
break;
case 'h':
printf(":Manual mode:\n");
times = atoi(optarg);
break;
case '?':
printf("Unknow\n");
exit(0);
break;
default:
break;
}
}
gpioInitialise();
if (gpioSetMode(18, PI_OUTPUT) < 0)
{
printf("Failed\n");
exit(0);
}
else
{
printf("Pigpio initialised ...\n");
}
gpioWrite(18, 0);
printf("Watering...\n");
signal(SIGINT, sig_handler);
for (int i = 0; i < times; i++)
{
printf("The %d th time \n", i + 1);
gpioWrite(18, 1);
sleep(30);
printf("%d th time dome. System cooling...\n",i+1);
gpioWrite(18, 0);
sleep(50);
}
printf("Done.\n");
gpioWrite(18, 0);
return 0;
}
Views: 133