[patch] on_exit.3: Add example code

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Example tries to clarify one should not refer to variables that are not in
on_exit() scope.  Such variables include heap in main().  In short only
variables allocated from stack make is sense when calling on_exit().
Possible referal to global variables would technically work, but at the same
go makes function argument pointless and in such case one ought to prefer
atexit() instead.

Signed-off-by: Sami Kerola <kerolasa@xxxxxx>
---
 man3/on_exit.3 | 40 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 40 insertions(+)

diff --git a/man3/on_exit.3 b/man3/on_exit.3
index d2c2c3b17..c074cda76 100644
--- a/man3/on_exit.3
+++ b/man3/on_exit.3
@@ -100,6 +100,46 @@ It no longer occurs in Solaris (SunOS 5).
 Portable application should avoid this function, and use the standard
 .BR atexit (3)
 instead.
+.SH EXAMPLE
+Following program uses
+.BR on_exit (3)
+to display data, that is allocated until processing is done.
+Notice that variables main() in heap are not in on_exit() scope.
+.PP
+.EX
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+struct data {
+    int argc;
+    char *argv;
+};
+
+static void run_on_exit(int exit_val, void *arg)
+{
+    struct data *d = (struct data *)arg;
+
+    printf("argc: %d argv: %s\n", d->argc, d->argv);
+    free(d->argv);
+    free(d);
+    _exit(exit_val);
+}
+
+int main(int argc, char **argv)
+{
+    struct data *d;
+
+    if (1 < argc) {
+        d = malloc(sizeof(*d));
+        d->argc = argc;
+        d->argv = strdup(argv[1]);
+        on_exit(run_on_exit, d);
+    }
+    return 0;
+}
+.EE
 .SH SEE ALSO
 .BR _exit (2),
 .BR atexit (3),
-- 
2.21.0




[Index of Archives]     [Kernel Documentation]     [Netdev]     [Linux Ethernet Bridging]     [Linux Wireless]     [Kernel Newbies]     [Security]     [Linux for Hams]     [Netfilter]     [Bugtraq]     [Yosemite News]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux Admin]     [Samba]

  Powered by Linux