03-Linux环境

Linux 环境

程序参数

int main(int argc,           // 参数数量
         char const *argv[]  // 字符串数组,第一个是调用程序的名称
) {
  for (int i = 0; i < argc; ++i) {
      if (argv[i][0] == '-') {
          std::cout << "option:" << argv[i] << std::endl;
      } else {
          std::cout << "argument:" << argv[i] << std::endl;
      }
  }
  return 0;
}

getopt 函数

// unistd.h
// getopt.h
extern int getopt (int ___argc,             // 参数数目
                   char *const *___argv,    // 参数字符串数组
                   const char *__shortopts  // 代表一个单选项字符,“--”类型参数无法处理
                                            // : 用于处理关联值,通过optarg获取,未指定则复制 ?
                  );
extern char *optarg;
extern int optind,   // 下一个待处理参数的索引,getopt用其记录长度
           opterr, 
           optopt;

支持需要关联值与不需要关联值的选项。

int main(int argc,     // 参数数量
         char *argv[]  // 字符串数组,第一个是调用程序的名称
) {
  int opt = 0;
  while ((opt = getopt(argc, argv, ":if:lr")) != -1) {
    switch (opt) {
      case 'i':
      case 'l':
      case 'r':
        std::printf("option : %c\n", opt);
        break;
      case 'f':          // 使用 f: 将'-f'后的参数赋值给 optarg 变量
        std::printf("parameter : %s\n", optarg);
        break;
      case ':':
        std::printf("option needs a value");
        break;
      case '?':
        std::printf("unknown option : %c\n", optopt);
        break;
      default:
        break;
    }
  }

  for (; optind < argc; optind++) {
    std::printf("argument : %s\n", argv[optind]);
  }

  return 0;
}

./env -i -lr 'hi there' -f 'fred.c' -q 'sdsdd' 'dsdsd'
option : i
option : l
option : r
parameter : fred.c
unknown option : q
argment : hi there
argment : sdsdd
argment : dsdsd

getopt_long

与前者类似,支持 -- 类型的参数

extern int getopt_long_only (int ___argc, 
                             char *__getopt_argv_const *___argv,
                             const char *__shortopts,    // 与前者相同
                             const struct option *__longopts, // 描述了每个长选项,并指定如何处理
                             int *__longind  // 可以作为optind的长选项版使用
                            );

struct option
{
  const char *name;  // 长选项名字
  int has_arg;       // 是否带参数
  int *flag;         // 为NULL时函数返回val里的值,否则返回0,并将值写入flag指向的变量。
  int val;           // 该选项的返回值
};
#include <getopt.h>
#include <cstdio>

int main(int argc,     // 参数数量
         char *argv[]  // 字符串数组,第一个是调用程序的名称
)
{
    int opt;
    struct option longopts[] = {{"initialize", 0, NULL, 'i'},
                                {"file", 1, NULL, 'f'},
                                {"list", 0, NULL, 'l'},
                                {"restart", 0, NULL, 'r'},
                                {0, 0, 0, 0}};

    while ((opt = getopt_long(argc, argv, ":if:lr", longopts, NULL)) != -1) {
        switch (opt) {
        case 'i':
        case 'l':
        case 'r':
            std::printf("option : %c\n", opt);
            break;
        case 'f':  // 使用 f: 将'-f'后的参数赋值给 optarg 变量
            std::printf("parameter : %s\n", optarg);
            break;
        case ':':
            std::printf("option needs a value");
            break;
        case '?':
            std::printf("unknown option : %c\n", optopt);
            break;
        default:
            break;
        }
    }

    for (; optind < argc; optind++) {
        std::printf("argument : %s\n", argv[optind]);
    }
    return 0;
}

./env.exe --initialize --list 'hi there' --file 'fred.c' -q
option : i
option : l
parameter : fred.c
unknown option : q
argument : hi there

环境变量

int putenv(const char *string) 设置环境变量 ,如果不存在返回NULL,如果存在返回一个空字符串。返回的字符串存储在静态控件,如要使用需要将其复制到其他空间,防止被覆盖。

char *setenv(const char *name) 设置环境变量,使用“名字=值”。

时间 日期

time.h 头文件中 time_t 来处理。

int main(int argc, char const *argv[])
{
    time_t the_time;

    the_time = time(nullptr);     // 如果传入的不是空指针,将会把值写入指定空间中。
    printf("The time is %ld\n", the_time);
    return 0;
}
// 求时间差
extern double difftime (time_t __time1, time_t __time0);

// 获取特定的表示时间的结构体
extern struct tm *gmtime (const time_t *__timer);

// 结构体的定义
struct tm
{
  int tm_sec;			/* Seconds.	[0-60] (1 leap second) */
  int tm_min;			/* Minutes.	[0-59] */
  int tm_hour;			/* Hours.	[0-23] */
  int tm_mday;			/* Day.		[1-31] */
  int tm_mon;			/* Month.	[0-11] */
  int tm_year;			/* Year	- 1900.  */
  int tm_wday;			/* Day of week.	[0-6] */
  int tm_yday;			/* Days in year.[0-365]	*/
  int tm_isdst;			/* DST.		[-1/0/1]*/

# ifdef	__USE_MISC
  long int tm_gmtoff;		/* Seconds east of UTC.  */
  const char *tm_zone;		/* Timezone abbreviation.  */
# else
  long int __tm_gmtoff;		/* Seconds east of UTC.  */
  const char *__tm_zone;	/* Timezone abbreviation.  */
# endif
};

// 默认使用UTC
// 将时间戳转换为本地时间
extern struct tm *localtime (const time_t *__timer);

// 将 tm 结构转为time_t,不能转换返回 -1
extern time_t mktime (struct tm *__tp);

// 获得人类友好的字符串时间
extern char *asctime (const struct tm *__tp);

/* Equivalent to `asctime (localtime (timer))'.  */
extern char *ctime (const time_t *__timer) __THROW;

// 从一个代表日期和时间的字符串获得 tm 结构
extern char *strptime (const char *__restrict __s,   // Thu 26 July 2007, 17:53
                       const char *__restrict __fmt, // %A %d %B, %I:%S %p
                       struct tm *__tp);             // 接收 tm 结构
                       // 返回值为不能解析的第一个字符指针位置

临时文件

char *tmpnam(char *s); 返回一个不重复的有效文件名

FILE *tmpfile(void); 返回一个文件流指针,指向唯一的临时文件。通过读写方式打开,对它的全部引用关闭时,自动删除。

#include <time.h>
#include <stdio.h>

int main(int argc, char const *argv[])
{
    char tmpname[L_tmpnam];
    char *filename;
    FILE *tmpfp;

    filename = tmpnam(tmpname);
    printf("Temporary file name is: %s\n", filename);
    tmpfp = tmpfile();
    if (tmpfp) {
        printf("Opened a temporary file OK\n");
    } else {
        perror("tmpfile");
    }
    fclose(tmpfp);

    return 0;
}

用户信息

UUID有独特的类型 uid_t 定义在 sys/types.h 中。

#include <sys/types.h>
#include <unistd.h>
uid_t getuid(void);   // 返回程序关联的 UID,通常时启动程序的用户ID
char *getlogin(void); // 返回当前用户关联的登录名

#include <sys/types.h>
#include <pwd.h>
struct passwd *getpwuid(uid_t uid);
struct passwd *getpwnam(const char *name);

/* The passwd structure.  */
struct passwd
{
  char *pw_name;		/* Username.  */
  char *pw_passwd;		/* Password.  */
  __uid_t pw_uid;		/* User ID.  */
  __gid_t pw_gid;		/* Group ID.  */
  char *pw_gecos;		/* Real name.  */
  char *pw_dir;			/* Home directory.  */
  char *pw_shell;		/* Shell program.  */
};

主机信息

#include <sys/utsname.h>
#include <unistd.h>

// 主机网络名写入name字符串,字符串长为namelen。成功返回0,失败返回-1
int gethostname(char *name, size_t namelen);

// 返回描述计算机的数据结构
int uname(struct utsname *name);

// 详细描述计算机的数据结构
struct utsname
  {
    /* Name of the implementation of the operating system.  */
    char sysname[_UTSNAME_SYSNAME_LENGTH];

    /* Name of this node on the network.  */
    char nodename[_UTSNAME_NODENAME_LENGTH];

    /* Current release level of this implementation.  */
    char release[_UTSNAME_RELEASE_LENGTH];
    
    /* Current version level of this release.  */
    char version[_UTSNAME_VERSION_LENGTH];

    /* Name of the hardware type the system is running on.  */
    char machine[_UTSNAME_MACHINE_LENGTH];
  };

日志

/var/log/messages 包含所有系统信息

/var/log/mail 包含邮件系统的其他日志

/var/log/debug 包含调试信息

/etc/syslog/conf/etc/syslog-ng/syslog-ng.conf检查系统日志配置

#include <syslog.h>

void syslog(int priority, const char *message, arguments...);

// priority
#define	LOG_EMERG	0	/* system is unusable */
#define	LOG_ALERT	1	/* action must be taken immediately */
#define	LOG_CRIT	2	/* critical conditions */
#define	LOG_ERR		3	/* error conditions */
#define	LOG_WARNING	4	/* warning conditions */
#define	LOG_NOTICE	5	/* normal but significant condition */
#define	LOG_INFO	6	/* informational */
#define	LOG_DEBUG	7	/* debug-level messages */

资源与限制

UNIX规范定义了一些可以由程序员定义决定的限制。

limits.h
    
NAME_MAX   文件名中最大字符数
CHAR_BIT   char类型值的位数
CHAR_MAX   char类型的最大值
INT_MAX    int类型的最大值
#include <sys/resource.h>

// 获取设置进程优先级
extern int getpriority (__priority_which_t __which, id_t __who) __THROW;
extern int setpriority (__priority_which_t __which, id_t __who, int __prio) __THROW;
// id_t 是一个整数类型,用于用户和组的标识符


// 获得与设置系统资源限制
extern int getrlimit (__rlimit_resource_t __resource,
		             struct rlimit *__rlimits) __THROW;
extern int setrlimit (__rlimit_resource_t __resource,
		             const struct rlimit *__rlimits) __THROW;
extern int getrusage (__rusage_who_t __who, struct rusage *__usage) __THROW;


posted @ 2022-06-16 09:39  某某人8265  阅读(31)  评论(0编辑  收藏  举报