631a216c800f29c858e6ed33c2dd475e1fe59191
[platform/core/system/libsystem.git] / src / libsystem / libsystem.h
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /*
4  * libsystem
5  *
6  * Copyright (c) 2014 Samsung Electronics Co., Ltd.
7  *
8  * Licensed under the Apache License, Version 2.0 (the License);
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  */
20
21 /**
22  * @file libsystem.h
23  *
24  * system utility library
25  *
26  * Copyright (c) 2016 Samsung Electronics Co., Ltd. All rights reserved.
27  *
28  */
29
30 #pragma once
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <stdint.h>
35 #ifndef __cplusplus
36 #include <stdbool.h>
37 #endif
38 #include <unistd.h>
39 #include <string.h>
40 #include <dirent.h>
41
42 #ifdef __cplusplus
43 extern "C" {
44 #endif
45
46 /**
47  * Many functions have no effects except the return value and their
48  * return value depends only on the parameters and/or global
49  * variables. Such a function can be subject to common subexpression
50  * elimination and loop optimization just as an arithmetic operator
51  * would be. These functions should be declared with the attribute
52  * pure.
53  */
54 #define _pure_ __attribute__ ((pure))
55
56 /**
57  * The cleanup attribute runs a function when the variable goes out of
58  * scope. This attribute can only be applied to auto function scope
59  * variables; it may not be applied to parameters or variables with
60  * static storage duration. The function must take one parameter, a
61  * pointer to a type compatible with the variable. The return value of
62  * the function (if any) is ignored.
63  */
64 #define _cleanup_(x) __attribute__((cleanup(x)))
65
66 /**
67  * whitespaces such like space, tab or newlines
68  */
69 #define WHITESPACE " \t\n\r"
70
71 /**
72  * newlines
73  */
74 #define NEWLINE "\n\r"
75
76 /**
77  * single or double quotes
78  */
79 #define QUOTES "\"\'"
80
81 /**
82  * comment start specifiers such like sharp(#) or semicolon(;)
83  */
84 #define COMMENTS "#;"
85
86 /**
87  * @defgroup GCC_CLEANUP_ATT_GROUP gcc cleanup attribute
88  *
89  * @{
90  */
91
92 static inline void __cleanup_free_func(void *p) {
93         free(*(void**) p);
94 }
95
96 static inline void __cleanup_close_func(int *fd) {
97         if (*fd >= 0)
98                 close(*fd);
99 }
100
101 static inline void __cleanup_fclose_func(FILE **f) {
102         if (*f)
103                 fclose(*f);
104 }
105
106 static inline void __cleanup_pclose_func(FILE **f) {
107         if (*f)
108                 pclose(*f);
109 }
110
111 static inline void __cleanup_closedir_func(DIR **d) {
112         if (*d)
113                 closedir(*d);
114 }
115
116 static inline const char *startswith(const char *s, const char *prefix) {
117         if (strncmp(s, prefix, strlen(prefix)) == 0)
118                 return s + strlen(prefix);
119         return NULL;
120 }
121
122 static inline bool isempty(const char *p) {
123         return !p || !p[0];
124 }
125
126 /**
127  * Declare value with cleanup attribute. free() is called when is
128  * going out the scope.
129  */
130 #define _cleanup_free_ _cleanup_(__cleanup_free_func)
131
132 /**
133  * Declare value with cleanup attribute. close() is called when is
134  * going out the scope.
135  */
136 #define _cleanup_close_ _cleanup_(__cleanup_close_func)
137
138 /**
139  * Declare value with cleanup attribute. fclose() is called when is
140  * going out the scope.
141  */
142 #define _cleanup_fclose_ _cleanup_(__cleanup_fclose_func)
143
144 /**
145  * Declare value with cleanup attribute. pclose() is called when is
146  * going out the scope.
147  */
148 #define _cleanup_pclose_ _cleanup_(__cleanup_pclose_func)
149
150 /**
151  * Declare value with cleanup attribute. closedir() is called when is
152  * going out the scope.
153  */
154 #define _cleanup_closedir_ _cleanup_(__cleanup_closedir_func)
155 /**
156  * @}
157  */
158
159 /**
160  * Allocate n number of size t memory.
161  */
162 #define new(t, n) ((t*) malloc(sizeof(t) * (n)))
163
164 /**
165  * Allocate n number of size t memory. And initialize to 0 all.
166  */
167 #define new0(t, n) ((t*) calloc((n), sizeof(t)))
168
169 /**
170  * Allocate n number memory.
171  */
172 #define malloc0(n) (calloc((n), 1))
173
174 /**
175  * @brief Parse boolean type string.
176  *
177  * @param v String to parse.
178  *
179  * @return TRUE on "1", 'y', 'Y', 't', 'T' and "on". FALSE on "0",
180  * 'n', 'N', 'f', 'F', "off".
181  */
182 int parse_boolean(const char *v) _pure_;
183
184 /**
185  * @brief Parse byte type string.
186  *
187  * @param b Byte string. This can be only digit number with byte unit
188  * "BKMG". B is byte, K is kilo byte, M is mega byte and G is gira
189  * byte. Byte is default.
190  * @param s Parsed byte size is filled.
191  *
192  * @return 0 on success, -errno on failure.
193  */
194 int parse_bytes(const char *b, size_t *s) _pure_;
195
196 /**
197  * @brief Parse percentage type string.
198  *
199  * @param string Percentage string to parse. Such like "70%".
200  * @param percent Parsed percentage size is filled.
201  *
202  * @return 0 on success, -errno on failure.
203  */
204 int parse_percent(const char *string, size_t *percent) _pure_;
205
206 /**
207  * @brief check the path string is started with '/'
208  *
209  * @param p a path to check
210  *
211  * @return true if p started with '/', otherwise false.
212  */
213 bool path_is_absolute(const char *p);
214
215 /**
216  * @brief Removes redundant inner and trailing slashes. Modifies the
217  * passed string in-place. For example, if "///foo//bar/" is given
218  * then the path will be changed as "/foo/bar"
219  *
220  * @param path a path to modify.
221  *
222  * @return modified path pointer. It maybe identical with given path.
223  */
224 char *path_kill_slashes(char *path);
225
226 /**
227  * Get element number of array.
228  */
229 #define ELEMENTSOF(x) (sizeof(x)/sizeof((x)[0]))
230
231 /**
232  * Iterate for each struct reference.
233  */
234 #define FOREACH_STRUCT_REF(s, f, i)                  \
235         for ((i) = 0; s[(i)].f != NULL; (i)++)
236
237 /**
238  * @brief Iterate for each directory entries exclude "." and "..".
239  */
240 #define FOREACH_DIRENT(de, d, on_error)                                 \
241         for (errno = 0, de = readdir(d);; errno = 0, de = readdir(d))   \
242                 if (!de) {                                              \
243                         if (errno > 0) {                                \
244                                 on_error;                               \
245                         }                                               \
246                         break;                                          \
247                 } else if (streq(de->d_name, ".") ||                    \
248                            streq(de->d_name, ".."))                     \
249                         continue;                                       \
250                 else
251
252 /**
253  * @brief Check string is digit.
254  *
255  * @param s String to check.
256  * @param l Length to check.
257  *
258  * @return TRUE on all the characters are digit. FALSE on the others.
259  */
260 bool is_number(const char *s, int l);
261
262 /**
263  * @brief Run cp with given src, dst with option. Internally, directly
264  * calls /bin/cp with given arguments.
265  * @todo change direct calls of /bin/cp to c api.
266  *
267  * @param src source
268  * @param dst destination
269  * @param option cp option
270  * @param timeout_msec timeout milliseconds
271  *
272  * @return return exit code of /bin/cp or negative errno.
273  */
274 int do_copy(const char *src, const char *dst, const char *option, int64_t timeout_msec);
275
276 /**
277  * @brief Make a directory. If parent directories are also absent,
278  * make them also. Corresponding with "mkdir -p".
279  *
280  * @param path Path to make directory.
281  * @param mode The directory mode.
282  *
283  * @return 0 on success, -errno on failure.
284  */
285 int do_mkdir(const char *path, mode_t mode);
286
287 /**
288  * @brief Remove all elements in path recursivly.
289  *
290  * @param path Path to make directory.
291  *
292  * @return 0 on success, -errno on failure.
293  */
294 int rmdir_recursive(const char *path);
295
296 /**
297  * @defgroup FILE_READ_WRITE_GROUP File Read/Write utility
298  *
299  * @{
300  */
301
302 /**
303  * file write flags
304  */
305 enum file_write_flags {
306         /** Append line-end(\\n) at the end of file. In case of string
307          * write, if given string has already line-end characters
308          * then this flag has no effect. */
309         FILE_WRITE_NEWLINE_IF_NOT       =  1 << 0,
310         /** Run fflush(3) after file write. */
311         FILE_WRITE_WITH_FFLUSH          =  1 << 1,
312         /** Open file as append mode. */
313         FILE_WRITE_APPEND               =  1 << 2,
314 };
315
316 /**
317  * @brief Write strings to FILE
318  *
319  * @param f File pointer.
320  * @param str Strings to write.
321  * @param flags Optional flags to write file. For
322  * ::FILE_WRITE_NEWLINE_IF_NOT, if str has already line-end,
323  * ::FILE_WRITE_NEWLINE_IF_NOT will has no effect. For detail, see
324  * ::file_write_flags.
325  *
326  * @return 0 on success, -errno on failure.
327  */
328 int write_str_to_file(FILE *f, const char *str, enum file_write_flags flags);
329
330 /**
331  * @brief Write strings to path.
332  *
333  * @param path File path.
334  * @param str Strings to write.
335  * @param flags Optional flags to write file. For
336  * ::FILE_WRITE_NEWLINE_IF_NOT, if str has already line-end,
337  * ::FILE_WRITE_NEWLINE_IF_NOT will has no effect. For detail, see
338  * ::file_write_flags.
339  *
340  * @return 0 on success, -errno on failure.
341  */
342 int write_str_to_path(const char *path, const char *str, enum file_write_flags flags);
343
344 /**
345  * @brief Write signed decimal integer to FILE.
346  *
347  * @param f File pointer.
348  * @param i Signed integer to write.
349  * @param flags Optional flags to write file. if
350  * ::FILE_WRITE_NEWLINE_IF_NOT is set, line-end added. For detail, see
351  * ::file_write_flags.
352  *
353  * @return 0 on success, -errno on failure.
354  */
355 int write_int32_to_file(FILE *f, int32_t i, enum file_write_flags flags);
356
357 /**
358  * @brief Write signed decimal integer to path.
359  *
360  * @param path File path.
361  * @param i Signed integer to write.
362  * @param flags Optional flags to write file. if
363  * ::FILE_WRITE_NEWLINE_IF_NOT is set, line-end added. For detail, see
364  * ::file_write_flags.
365  *
366  * @return 0 on success, -errno on failure.
367  */
368 int write_int32_to_path(const char *path, int32_t i, enum file_write_flags flags);
369
370 /**
371  * @brief Write unsigned decimal integer to FILE.
372  *
373  * @param f File pointer
374  * @param u Unsigned integer to write.
375  * @param flags Optional flags to write file. if
376  * ::FILE_WRITE_NEWLINE_IF_NOT is set, line-end added. For detail, see
377  * ::file_write_flags.
378  *
379  * @return 0 on success, -errno on failure.
380  */
381 int write_uint32_to_file(FILE *f, uint32_t u, enum file_write_flags flags);
382
383 /**
384  * @brief Write unsigned decimal integer to path.
385  *
386  * @param path File path.
387  * @param u Unsigned integer to write.
388  * @param flags Optional flags to write file. if
389  * ::FILE_WRITE_NEWLINE_IF_NOT is set, line-end added. For detail, see
390  * ::file_write_flags.
391  *
392  * @return 0 on success, -errno on failure.
393  */
394 int write_uint32_to_path(const char *path, uint32_t u, enum file_write_flags flags);
395
396 /**
397  * @brief Read the first line from FILE
398  *
399  * @param f File pointer.
400  * @param line Duplicated string line is filled. This value has to
401  * be free-ed by caller.
402  *
403  * @return 0 on success, -errno on failure.
404  */
405 int read_one_line_from_file(FILE *f, char **line);
406
407 /**
408  * @brief Read the first line from path
409  *
410  * @param path File path.
411  * @param line Duplicated string line is filled. This value has to
412  * be free-ed by caller.
413  *
414  * @return 0 on success, -errno on failure.
415  */
416 int read_one_line_from_path(const char *path, char **line);
417
418 /**
419  * @brief Read signed decimal integer from FILE.
420  *
421  * @param f File pointer.
422  * @param i signed int value pointer.
423  *
424  * @return 0 on success, -errno on failure.
425  */
426 int read_int32_from_file(FILE *f, int32_t *i);
427
428 /**
429  * @brief Read signed decimalinteger from path.
430  *
431  * @param path File path.
432  * @param i signed int value pointer.
433  *
434  * @return 0 on success, -errno on failure.
435  */
436 int read_int32_from_path(const char *path, int32_t *i);
437
438 /**
439  * @brief Read unsigned decimalinteger from FILE.
440  *
441  * @param f File pointer.
442  * @param u unsigned int value pointer.
443  *
444  * @return 0 on success, -errno on failure.
445  */
446 int read_uint32_from_file(FILE *f, uint32_t *u);
447
448 /**
449  * @brief Read unsigned decimal integer from path
450  *
451  * @param path File path.
452  * @param u unsigned int value pointer.
453  *
454  * @return 0 on success, -errno on failure.
455  */
456 int read_uint32_from_path(const char *path, uint32_t *u);
457 /**
458  * @}
459  */
460
461 /**
462  * @defgroup STRING_GROUP String helper
463  *
464  * @{
465  */
466
467 /**
468  * Compare two strings. TRUE on same, FALSE on others.
469  * Same with (strcmp((a),(b)) == 0)
470  */
471 #define streq(a,b) (strcmp((a),(b)) == 0)
472 /**
473  * Compare two strings for n length. TRUE on same, FALSE on others.
474  * Same with (strncmp((a), (b), (n)) == 0)
475  */
476 #define strneq(a, b, n) (strncmp((a), (b), (n)) == 0)
477
478 /**
479  * Compare two strings. Similar to streq() but ignore case. TRUE on
480  * same, FALSE on others.
481  * Same with (strcasecmp((a),(b)) == 0)
482  */
483 #define strcaseeq(a,b) (strcasecmp((a),(b)) == 0)
484
485 /**
486  * Compare two strings for n length. Similar to strneq() but ignore
487  * case. TRUE on same, FALSE on others.
488  * Same with (strcasecmp((a),(b)) == 0)
489  */
490 #define strncaseeq(a, b, n) (strncasecmp((a), (b), (n)) == 0)
491
492 /**
493  * Iterate string in strings which include null characters.
494  * For example,
495  *\code{.c}
496 const char str[] = {
497         "foo\0"
498         "bar\0";
499 };
500
501 const char *s;
502
503 NULSTR_FOREACH(s, str) {
504         // do something here
505 }
506  *\endcode
507  */
508 #define NULSTR_FOREACH(i, l)                                    \
509         for ((i) = (l); (i) && *(i); (i) = strchr((i), 0)+1)
510
511 /**
512  * @brief Like streq(), but tries to make sense of NULL pointers.
513  *
514  * @param a String.
515  * @param b String.
516  *
517  * @return TRUE on same, FALSE on the others.
518  */
519 bool streq_ptr(const char *a, const char *b) _pure_;
520
521 /**
522  * @brief Truncate line end characters.
523  *
524  * @param s String to truncate.
525  *
526  * @return Result string.
527  */
528 char *truncate_nl(char *s);
529
530 /**
531  * @brief Append suffix string to sting s with size b.
532  *
533  * @param s Ahead string.
534  * @param suffix The second string.
535  * @param b suffix size to append.
536  *
537  * @return Result string. This string has to be free-ed by caller.
538  */
539 char *strnappend(const char *s, const char *suffix, size_t b);
540
541 /**
542  * @brief Append suffix string to sting s.
543  *
544  * @param s Ahead string.
545  * @param suffix The second string.
546  *
547  * @return Result string. This string has to be free-ed by caller.
548  */
549 char *strappend(const char *s, const char *suffix);
550
551 /**
552  * @brief Drops trailing whitespaces.
553  *
554  * @param s String.
555  *
556  * @return The pointer to the first non-space character.
557  */
558 char *strstrip(char *s);
559
560 /**
561  * @brief duplicate string without leading and trailing whitespaces
562  *
563  * @param str a target string to duplicate
564  * @param ret newly allocated string is filled
565  *
566  * @return 0 on success, -errno on failure.
567  */
568 int strdup_strip(const char *str, char **ret);
569
570 /**
571  * @brief duplicate string without leading and trailing whitespaces,
572  * duplicated string is not over given length len
573  *
574  * @param str a target string to duplicate
575  * @param len maxium length of duplicate
576  * @param ret newly allocated string is filled
577  *
578  * @return 0 on success, -errno on failure.
579  */
580 int strndup_strip(const char *str, size_t len, char **ret);
581
582 /**
583  * @brief nulstr is similar to string list but each strings ends with
584  * null and the strings are put at one memory buffer. For example,
585  * "foo" and "bar" string can be represented "foo\0bar". This function
586  * check nulstr is containing the needle string.
587  *
588  * @param nulstr a nulstr
589  * @param needle a needle string to find
590  *
591  * @return true if the needle found, otherwise false.
592  */
593 bool nulstr_contains(const char*nulstr, const char *needle);
594
595 /**
596  * @brief check a string ends with postfix pattern
597  *
598  * @param s a string to check
599  * @param postfix postfix string
600  *
601  * @return if s is ended with postfix string the pointer of the
602  * string, matched pointer of s is returned. Otherwise NULL.
603  */
604 char* endswith(const char *s, const char *postfix);
605
606 /**
607  * @brief split a string into words. This api generally is not called
608  * directly, #FOREACH_WORD_SEPARATOR or #FOREACH_WORD are using
609  * this. If separator does not include quotes then quoted words are
610  * assumed as single word.
611  *
612  * @param c string to split
613  * @param l splitted word length
614  * @param separator separator strings such like #WHITESPACE
615  * @param state a state internally used
616  *
617  * @return a splitted current word pointer
618  */
619 char *split(const char *c, size_t *l, const char *separator, char **state);
620
621 /**
622  * @brief Iterate for each words. If separator does not include quotes
623  * then quoted words are assumed as single word.
624  *
625  * @param word Each word
626  * @param length Length of word
627  * @param s Target string
628  * @param separator Seperator string
629  * @param state Used only internal split().
630  */
631 #define FOREACH_WORD_SEPARATOR(word, length, s, separator, state)       \
632         for ((state) = NULL, (word) = split((s), &(length), (separator), &(state)); (word); (word) = split((s), &(length), (separator), &(state)))
633
634 /**
635  * @brief Iterate for each words. (Seperators are WHITESPACES.) Quoted
636  * words are assumed as single word.
637  *
638  * @param word Each word
639  * @param length Length of word
640  * @param s Target string
641  * @param state Used only internal split().
642  */
643 #define FOREACH_WORD(word, length, s, state)                            \
644         FOREACH_WORD_SEPARATOR(word, length, s, WHITESPACE, state)
645
646 /**
647  * @brief Duplicate string and strip quotes from the string.
648  *
649  * @param str String to duplicate.
650  * @param quotes Quote characters to strip. Predefined #QUOTES can be
651  * used to specify quote and double quote.
652  *
653  * @return Result string. This value has to be free-ed by caller.
654  */
655 char *strdup_unquote(const char *str, const char *quotes);
656 /**
657  * @}
658  */
659
660 /**
661  * @defgroup STRV_GROUP String List
662  *
663  * @{
664  */
665
666 /**
667  * iterate for each elements of string list.
668  */
669 #define FOREACH_STRV(s, l)                      \
670         for ((s) = (l); (s) && *(s); (s)++)
671
672 /**
673  * @brief Split given string to string list with separator.
674  *
675  * @param str string to split as string list.
676  * @param strv Splitted string list is filled. This string list has to
677  *   be free-ed.
678  * @param separator sperators to split the string.
679  *
680  * @return 0 on success, -errno on failure.
681  */
682 int str_to_strv(const char *str, char ***strv, const char *separator);
683
684 /**
685  * @brief Get elements of string list. #sizeof_strv() does not count
686  * end of list NULL. For example, for {"foo", "bar", NULL} string
687  * list, #sizeof_strv() returns 2.
688  *
689  * @param strv string list.
690  *
691  * @return number of string list.
692  */
693 size_t sizeof_strv(char **strv);
694
695 /**
696  * @brief Merge two string lists. If {"foo", "bar"} and {"baz", "qux"}
697  * are given, the result is {"foo", "bar", "baz", "quz"}.
698  *
699  * @param first The first string list.
700  * @param second The second string list.
701  * @param strv Merged string list.
702  * @param free_second If TRUE is given, the second string list will be
703  * free-ed. If FALSE, no action.
704  *
705  * @return number of string list.
706  */
707 int strv_attach(char **first, char **second, char ***strv, bool free_second);
708
709 /**
710  * @brief Free all given string list
711  *
712  * @param strv string list to free.
713  */
714 void strv_free_full(char **strv);
715 /**
716  * @}
717  */
718
719 /**
720  * @brief Check given path is directory or not
721  *
722  * @param path path to check
723  *
724  * @return TRUE if path is directory, FALSE on others.
725  */
726 bool isdir(const char *path);
727
728 /**
729  * @brief Simple file create api similar to touch(1)
730  *
731  * @param path file path
732  *
733  * @return 0 on success, -errno on failure.
734  */
735 int touch(const char *path);
736
737 /**
738  * @brief Check mount entry. Multiple matches of conditoin are able to
739  * be set with mnt_fsname, mnt_dir, mnt_type or mnt_opts. If multiple
740  * matches are given, return true if a entry satisfied all matches.
741  *
742  * \code{.c}
743 // check cgroup is mounted
744 if (is_mounted("cgroup", NULL, NULL, NULL))
745         printf("cgroup is mounted\n");
746
747 // check /tmp is mounted
748 if (is_mounted("tmpfs", "/tmp", NULL, NULL))
749         printf("/tmp is mounted\n");
750
751 // check cgroup is mounted as cgroup2
752 if (is_mounted("cgroup", "/sys/fs/cgroup", "cgroup2", NULL))
753         printf("cgroup is mounted as cgroup2\n");
754  * \endcode
755  *
756  * @param fsname find matched mount filesystem name
757  * @param dir find matched mount dir(path) name
758  * @param type find matched mount type name
759  * @param opts find matched mount option name
760  *
761  * @return true if matched mount entry found, otherwise false.
762  */
763 bool mnt_is_mounted(const char *fsname, const char *dir, const char *type, const char *opts);
764
765 /**
766  * @defgroup EXEC_GROUP exec group
767  *
768  * @brief fork() and exec() utility
769  * @{
770  */
771
772 /**
773  * standard output/error redirect flags
774  */
775 enum {
776         /**
777          * Do not redirect standard output/error
778          */
779         EXEC_REDIRECT_NONE      = 0x01 << 0,
780         /**
781          * Redirect standard output only
782          */
783         EXEC_REDIRECT_OUTPUT    = 0x01 << 1,
784         /**
785          * Redirect standard error only
786          */
787         EXEC_REDIRECT_ERROR     = 0x01 << 2,
788         /**
789          * Redirect standard output and error all
790          */
791         EXEC_REDIRECT_ALL       = (EXEC_REDIRECT_OUTPUT | EXEC_REDIRECT_ERROR),
792 };
793
794 /**
795  * @brief Traditional fork() and exec() helper. If child is not
796  * deactivated within given \p timeout_msec then kill it with given
797  * signal. And additionally redirect child process standard output or
798  * standard error to given fd.
799  *
800  * @param argv array of pointers to null-terminated strings that
801  * represent the argument list available to the new program. The first
802  * argument should point to the filename associated with the file
803  * being executed. The array of pointers must be terminated by a NULL
804  * pointer.
805  * @param envp specify the environment of the executed program via the
806  * argument envp. The envp argument is an array of pointers to
807  * null-terminated strings and must be terminated by a NULL pointer.
808  * @param timeout_msec timeout millisecond to prevent infinite
809  * waiting. If negative is given, the parent will not wait the
810  * child. In other word, the parent will return immediately. If 0 is
811  * given, parent will wait the child infinitly. And if positive value
812  * is given parent will wait given milliseconds and expired return
813  * -1. If the child is exit within the tiemout millisecond return with
814  * child exit code.
815  * @param sig signal to kill the child on timeout.
816  * @param fd file descriptor to redirect child standard output or
817  * error.
818  * @param flags redirect flag. This flags is able to include
819  * EXEC_REDIRECT_OUTPUT or EXEC_REDIRECT_ERROR.
820  *
821  * @return exit code of child. It is fully depend on the child
822  * process. If the child exit with 1 then this function also return 1.
823  * Negative errno on error. -ETIME on timer expired.
824  */
825 int do_fork_exec_kill_redirect(char *const argv[], char * const envp[], int64_t timeout_msec, int sig, int fd, int flags);
826
827 /**
828  * @brief Traditional fork() and exec() helper. And additionally
829  * redirect child process standard output or standard error to given fd.
830  *
831  * @param argv array of pointers to null-terminated strings that
832  * represent the argument list available to the new program. The first
833  * argument should point to the filename associated with the file
834  * being executed. The array of pointers must be terminated by a NULL pointer.
835  * @param envp specify the environment of the executed program via the
836  * argument envp. The envp argument is an array of pointers to
837  * null-terminated strings and must be terminated by a NULL pointer.
838  * @param timeout_msec timeout millisecond to prevent infinite
839  * waiting. If negative is given, the parent will not wait the
840  * child. In other word, the parent will return immediately. If 0 is
841  * given, parent will wait the child infinitly. And if positive value
842  * is given parent will wait given milliseconds and expired return
843  * -1. If the child is exit within the tiemout millisecond return with
844  * child exit code.
845  * @param fd file descriptor to redirect child standard output or error.
846  * @param flags redirect flag. This flags is able to include
847  * EXEC_REDIRECT_OUTPUT or EXEC_REDIRECT_ERROR.
848  *
849  * @return exit code of child. It is fully depend on the child
850  * process. If the child exit with 1 then this function also return 1.
851  * Negative errno on error. -ETIME on timer expired.
852  */
853 int do_fork_exec_redirect(char *const argv[], char * const envp[], int64_t timeout_msec, int fd, int flags);
854
855 /**
856  * @brief Traditional fork() and exec() helper. If child is not
857  * deactivated within given \p timeout_msec then kill it with given
858  * signal.
859  *
860  * @param argv array of pointers to null-terminated strings that
861  * represent the argument list available to the new program. The first
862  * argument should point to the filename associated with the file
863  * being executed. The array of pointers must be terminated by a NULL pointer.
864  * @param envp specify the environment of the executed program via the
865  * argument envp. The envp argument is an array of pointers to
866  * null-terminated strings and must be terminated by a NULL pointer.
867  * @param timeout_msec timeout millisecond to prevent infinite
868  * waiting. If negative is given, the parent will not wait the
869  * child. In other word, the parent will return immediately. If 0 is
870  * given, parent will wait the child infinitly. And if positive value
871  * is given parent will wait given milliseconds and expired return
872  * -1. If the child is exit within the tiemout millisecond return with
873  * child exit code.
874  * @param sig signal to kill the child on timeout.
875  *
876  * @return exit code of child. It is fully depend on the child
877  * process. If the child exit with 1 then this function also return 1.
878  * Negative errno on error. -ETIME on timer expired.
879  */
880 int do_fork_exec_kill(char *const argv[], char * const envp[], int64_t timeout_msec, int sig);
881
882 /**
883  * @brief Traditional fork() and exec() helper.
884  *
885  * @param argv array of pointers to null-terminated strings that
886  * represent the argument list available to the new program. The first
887  * argument should point to the filename associated with the file
888  * being executed. The array of pointers must be terminated by a NULL pointer.
889  * @param envp specify the environment of the executed program via the
890  * argument envp. The envp argument is an array of pointers to
891  * null-terminated strings and must be terminated by a NULL pointer.
892  * @param timeout_msec timeout millisecond to prevent infinite
893  * waiting. If negative is given, the parent will not wait the
894  * child. In other word, the parent will return immediately. If 0 is
895  * given, parent will wait the child infinitly. And if positive value
896  * is given parent will wait given milliseconds and expired return
897  * -1. If the child is exit within the tiemout millisecond return with
898  * child exit code.
899  *
900  * @return exit code of child. It is fully depend on the child
901  * process. If the child exit with 1 then this function also return 1.
902  * Negative errno on error. -ETIME on timer expired.
903  */
904 int do_fork_exec(char *const argv[], char * const envp[], int64_t timeout_msec);
905
906 /**
907  * @}
908  */
909
910 /**
911  * @defgroup TIME_UTIL_GROUP time util group
912  *
913  * @brief time utility libraries
914  * @{
915  */
916
917 /** millisecond per second */
918 #define MSEC_PER_SEC            1000ULL
919 /** microsecond per second */
920 #define USEC_PER_SEC            ((uint64_t) 1000000ULL)
921 /** microsecond per millisecond */
922 #define USEC_PER_MSEC           ((uint64_t) 1000ULL)
923 /** nanosecond per second */
924 #define NSEC_PER_SEC            ((uint64_t) 1000000000ULL)
925 /** nanosecond per microsecond */
926 #define NSEC_PER_MSEC           ((uint64_t) 1000000ULL)
927 /** nanosecond per microsecond */
928 #define NSEC_PER_USEC           ((uint64_t) 1000ULL)
929
930 /** microsecond per minute */
931 #define USEC_PER_MINUTE         ((uint64_t) (60ULL*USEC_PER_SEC))
932 /** nanosecond per minute */
933 #define NSEC_PER_MINUTE         ((uint64_t) (60ULL*NSEC_PER_SEC))
934 /** microsecond per hour */
935 #define USEC_PER_HOUR           ((uint64_t) (60ULL*USEC_PER_MINUTE))
936 /** nanosecond per hour */
937 #define NSEC_PER_HOUR           ((uint64_t) (60ULL*NSEC_PER_MINUTE))
938 /** microsecond per day */
939 #define USEC_PER_DAY            ((uint64_t) (24ULL*USEC_PER_HOUR))
940 /** nanosecond per day */
941 #define NSEC_PER_DAY            ((uint64_t) (24ULL*NSEC_PER_HOUR))
942 /** microsecond per week */
943 #define USEC_PER_WEEK           ((uint64_t) (7ULL*USEC_PER_DAY))
944 /** nanosecond per week */
945 #define NSEC_PER_WEEK           ((uint64_t) (7ULL*NSEC_PER_DAY))
946 /** microsecond per month */
947 #define USEC_PER_MONTH          ((uint64_t) (2629800ULL*USEC_PER_SEC))
948 /** nanosecond per month */
949 #define NSEC_PER_MONTH          ((uint64_t) (2629800ULL*NSEC_PER_SEC))
950 /** microsecond per year */
951 #define USEC_PER_YEAR           ((uint64_t) (31557600ULL*USEC_PER_SEC))
952 /** nanosecond per year */
953 #define NSEC_PER_YEAR           ((uint64_t) (31557600ULL*NSEC_PER_SEC))
954
955 /** frequently used time format string: 12:34 */
956 #define HH_MM                           "%H:%M"
957 /** frequently used time format string: 12:34:56 */
958 #define HH_MM_SS                        "%H:%M:%S"
959
960 /** frequently used time format string: 2015-01-23 */
961 #define YYYY_MM_DD                      "%Y-%m-%d"
962 /** frequently used time format string: 2015-01-23 12:34 */
963 #define YYYY_MM_DD_HH_MM                "%Y-%m-%d %H:%M"
964 /** frequently used time format string: 2015-01-23 12:34:56 */
965 #define YYYY_MM_DD_HH_MM_SS             "%Y-%m-%d %H:%M:%S"
966 /** frequently used time format string: 2015-01-23 12:34:56 KST */
967 #define YYYY_MM_DD_HH_MM_SS_Z           "%Y-%m-%d %H:%M:%S %Z"
968
969 /** frequently used time format string: Fri 2015-01-23 */
970 #define DOW_YYYY_MM_DD                  "%a %Y-%m-%d"
971 /** frequently used time format string: Fri 2015-01-23 12:34 */
972 #define DOW_YYYY_MM_DD_HH_MM            "%a %Y-%m-%d %H:%M"
973 /** frequently used time format string: Fri 2015-01-23 12:34:56 */
974 #define DOW_YYYY_MM_DD_HH_MM_SS         "%a %Y-%m-%d %H:%M:%S"
975 /** frequently used time format string: Fri 2015-01-23 12:34:56 KST */
976 #define DOW_YYYY_MM_DD_HH_MM_SS_Z       "%a %Y-%m-%d %H:%M:%S %Z"
977
978 /**
979  * @brief Convert time_t to given format time string.
980  *
981  * @param sec time second to convert
982  * @param format format string
983  * @param time string pointer to converted time is filled. On
984  * successful return, this value has to be free-ed by caller.
985  *
986  * @return 0 on success, -errno on failure.
987  */
988 int sec_to_timestr(time_t sec, const char *format, char **time);
989
990 /**
991  * @brief Convert time_t to \%a \%Y-\%m-\%d \%H:\%M:\%S \%Z format time string.
992  *
993  * @param sec time second to convert
994  * @param time string pointer to converted time is filled. On
995  * successful return, this value has to be free-ed by caller.
996  *
997  * @return 0 on success, -errno on failure.
998  */
999 int sec_to_timestr_full(time_t sec, char **time);
1000
1001 /**
1002  * @brief Convert given format time string to time_t.
1003  *
1004  * @param format format string
1005  * @param time time string to convert to time_t
1006  * @param sec converted time_t
1007  *
1008  * @return 0 on success, -errno on failure.
1009  */
1010 int timestr_to_sec(const char *format, const char *time, time_t *sec);
1011
1012 /**
1013  * @brief Make struct timeval from millisecond
1014  *
1015  * @param msec millisecond to Convert
1016  * @param tv struct timeval to be filled
1017  */
1018 void msec_to_timeval(uint64_t msec, struct timeval *tv);
1019
1020 /**
1021  * @}
1022  */
1023
1024 #ifdef __cplusplus
1025 }
1026 #endif