2019年7月12日 星期五

C : strrchr() analyze and example get self executable directory function.

strrchr() function will return a pointer to the last occurrence.
char a[] = "abc123";
char *b = strrchr(a, '1');
printf("%s\n", b); // 123
printf("%d\n", b); // pointer to '1', in my machine is 229315
printf("%d\n", a);// pointer to 'a', in my machine is 229312
view raw gistfile1.txt hosted with ❤ by GitHub
Another example is modify from Advanced Linux Programming chapter 11.We can get a sub-sting without the occurrence with sub two pointer.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
int rval;
char link_target[1024];
char* last_slash;
size_t result_length;
char* result;
/* Read the target of the symbolic link /proc/self/exe. */
rval = readlink ("/proc/self/exe", link_target, sizeof (link_target));
printf("%s\n", link_target);
if (rval == -1)
/* The call to readlink failed, so bail. */
abort ();
else
link_target[rval] = '\0';/* NUL-terminate the target. */
/* We want to trim the name of the executable file, to obtain the
directory that contains it. Find the rightmost slash. */
last_slash = strrchr (link_target, '/');
if (last_slash == NULL || last_slash == link_target)
/* Something strange is going on. */
abort ();
/* Allocate a buffer to hold the resulting path. */
result_length = last_slash - link_target ;
result = (char*) malloc (result_length + 1);
/* Copy the result. */
strncpy (result, link_target, result_length);
result[result_length] = '\0';
printf("%s\n", result);
return 0;
}
view raw gistfile1.txt hosted with ❤ by GitHub





Ref:
   1. http://www.cplusplus.com/reference/cstring/strrchr/
   2. Advanced Linux Programming by Mark Mitchell, Jeffrey Oldham, and Alex Samuel www.newriders.com

Linux driver: How to enable dynamic debug at booting time for built-in driver.

 Dynamic debug is useful for debug driver, and can be enable by: 1. Mount debug fs #>mount -t debugfs none /sys/kernel/debug 2. Enable dy...