C _application - RicoJia/notes GitHub Wiki

Basic Utils

getopt

  • sample usage
#include <unistd.h>
while (opt = getopt(argc, argv, ":if:"i) != -1)){// -1 means no more options to process
	// if no recoginized option is given, ? is returned
	//f: means option f requires an option. if no option is given, getopt returns ?
	// if starting with :, getopt will return : instead of ? when no value is given for f. 
	switch (opt){
		case 'i': 
			do_stuff(); 
		case 'f':
			printf("input args: %s", optarg); 
			break; 
		case '?': 
			break; 
		}
}
- opt is option
- optarg is the argument, **A global variable**
- optind is number of arguments. 
- Misc 
	- **If you see errors, check if you have break in case.**
  • std::getenv
    • Basics
     #include <cstdlib>
     const char* env_p = std::getenv("PATH"); 

Operating System

  • signal
    • the right hand side is the handler.
    • signal(SIGINT, somefunc) //this will hijack ctrl-c
    • signal(SIGPIPE, SIG_IGN) //ignore broken pipe? (the process reading a pipe or socket. SIG_IGN means to ignore it.)
    • signal(SIGTERM, finish) //SIGTERM is an administrative signal sent by another process to terminate. Kernel will never send this.

Random Numbers

  1. pseudo-random: to generate [0,n)
    1. rand() 是[0,RAND_MAX],两个在中define. 如果你要generate [0,n)的话,那么你会不会选择rand%(n)呢? 其实不要这么做。
    2. 当n 比较小时,比方说n=2),那么最后很有可能是0,1 alternate 的。
    3. 还有,比如RAND_MAX为32768,假如n = 20000, 那么[0,12768]的数可以被两个rand 值产生。 而剩下[12768,20000)只有一个数相对应。 所以,你可以:int r, bin_size; bin_size = RAND_MAX/n; do r = rand()/bin_size; while(r>=n); (discard 那些最靠近RAND_MAX的数)
  2. rand() may not generate evenly distributed values, instead in C++11:
    #include <random>
    #include <iostream>
     
    int main()
    {
        std::random_device rd;  //Will be used to obtain a seed for the random number engine
        std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
        std::uniform_int_distribution<> distrib(1, 6);
     
        for (int n=0; n<10; ++n)
            //Use `distrib` to transform the random unsigned int generated by gen into an int in [1, 6]
            std::cout << distrib(gen) << ' ';
        std::cout << '\n';
    }
    
⚠️ **GitHub.com Fallback** ⚠️