顯示具有 Linux Program 標籤的文章。 顯示所有文章
顯示具有 Linux Program 標籤的文章。 顯示所有文章

2015年6月16日 星期二

[C] How to use mmap


$#include <stdio.h>$
$#include <fcntl.h>$
$#include <sys/types.h>$
$#include <sys/stat.h>$
$#include <unistd.h>$
$#include <sys/io.h>$
$#include <sys/mman.h>$

int main(int argc, char const *argv[])
{
unsigned char *f;
int size;
struct stat s;
const char * file_name = argv[1];
int fd = open (argv[1], O_RDONLY);
/* Get the size of the file. */
int status = fstat (fd, & s);
size = s.st_size;

f = (char *) mmap (0, size, PROT_READ, MAP_PRIVATE, fd, 0);
for (int i = 0; i < size; i++) {
    char c;

    c = f[i];
    putchar(c);
}

return 0;
}

Reference:
- Reading a file to string with mmap

2015年3月12日 星期四

[Pipe] Example - Creating a Pipe


#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

/* Read characters from the pipe and echo them to stdout. */

void
read_from_pipe (int file)
{
  FILE *stream;
  int c;
  stream = fdopen (file, "r");
  while ((c = fgetc (stream)) != EOF)
    putchar (c);
  fclose (stream);
}

/* Write some random text to the pipe. */

void
write_to_pipe (int file)
{
  FILE *stream;
  stream = fdopen (file, "w");
  fprintf (stream, "hello, world!\n");
  fprintf (stream, "goodbye, world!\n");
  fclose (stream);
}

int
main (void)
{
  pid_t pid;
  int mypipe[2];

  /* Create the pipe. */
  if (pipe (mypipe))
    {
      fprintf (stderr, "Pipe failed.\n");
      return EXIT_FAILURE;
    }

  /* Create the child process. */
  pid = fork ();
  if (pid == (pid_t) 0)
    {
    printf("child  \n");
      /* This is the child process.
         Close other end first. */
      close (mypipe[1]);
      read_from_pipe (mypipe[0]);
      return EXIT_SUCCESS;
    }
  else if (pid < (pid_t) 0)
    {
      /* The fork failed. */
      fprintf (stderr, "Fork failed.\n");
      return EXIT_FAILURE;
    }
  else
    {
    printf("parent  \n");
      /* This is the parent process.
         Close other end first. */
      close (mypipe[0]);
      write_to_pipe (mypipe[1]);
      return EXIT_SUCCESS;
    }
}
Execute Code :
./a.out 
parent  
child  
hello, world!
goodbye, world!
Reference:

[C] Extract tokens from strings

Code :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define __SEC_POPEN_TOKEN " "

int main(void)
{
    char *ptr;
    char *strtokState;
    char cmdcpy[30] = "Happy Birthday";

    printf("%s \n",(ptr = strtok_r(cmdcpy, __SEC_POPEN_TOKEN, &strtokState)));
}

Execute code :
./a.out 
Happy 

Reference:

[C] Extract tokens from strings


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main(int argc, char *argv[])
{
    char *str1, *str2, *token, *subtoken;
    char *saveptr1 = NULL, *saveptr2 = NULL;
    int j;

   if (argc != 4) {
        fprintf(stderr, "Usage: %s string delim subdelim\n",
                argv[0]);
        exit(EXIT_FAILURE);
    }   

   for (j = 1, str1 = argv[1]; ; j++, str1 = NULL) {
        printf("saveptr1 = %s \n",saveptr1);
        token = strtok_r(str1, argv[2], &saveptr1);
        printf("str1 = %s, argv[2] = %s, saveptr1 = %s \n",str1, argv[2], saveptr1);
        printf("token = %s \n",token);
        if (token == NULL)
            break;
        printf("%d: %s\n", j, token);

       for (str2 = token; ; str2 = NULL) {
            subtoken = strtok_r(str2, argv[3], &saveptr2);
            if (subtoken == NULL)
                break;
            printf(" --> %s\n", subtoken);
        }
    }   

   exit(EXIT_SUCCESS);
}
Execute code :
./a.out 'a/bbb///cc;xxx:yyy:' ':;' '/'
saveptr1 = (null) 
str1 = a/bbb///cc, argv[2] = :;, saveptr1 = xxx:yyy: 
token = a/bbb///cc 
1: a/bbb///cc
 --> a
 --> bbb
 --> cc
saveptr1 = xxx:yyy: 
str1 = (null), argv[2] = :;, saveptr1 = yyy: 
token = xxx 
2: xxx
 --> xxx
saveptr1 = yyy: 
str1 = (null), argv[2] = :;, saveptr1 =  
token = yyy 
3: yyy
 --> yyy
saveptr1 =  
str1 = (null), argv[2] = :;, saveptr1 =  
token = (null) 
Reference:
strtok_r(3) - Linux man page

2015年3月9日 星期一

2014年7月2日 星期三

[Kernel Module] My first Kernel Module




Kernel Code 1


#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
static ssize_t drv_read(struct file *filp, char *buf, size_t count, loff_t *ppos)
{
printk
("device read\n");
return count;
}

static ssize_t drv_write(struct file *filp, const char *buf, size_t count, loff_t *ppos)
{
printk
("device write \n");
return count;
}

static int drv_open(struct inode *inode, struct file *filp)
{
printk
("device open \n");
return 0;
}


int drv_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg)
{
printk
("device ioctl \n");
return 0;
}

static int drv_release(struct inode *inode, struct file *filp)
{
printk
("device close \n");
return 0;
}

struct file_operations drv_fops =
{
read
: drv_read,
write
: drv_write,
compat_ioctl
: drv_ioctl,
open
: drv_open,
release
: drv_release,
};

#define MAJOR_NUM 60
#define MODULE_NAME "DEMO"
static int demo_init(void) {
if (register_chrdev(MAJOR_NUM, "demo", &drv_fops) < 0) {
printk
("<1>%s: can't get major %d\n", MODULE_NAME, MAJOR_NUM);
return (-EBUSY);
}

printk
("<1>%s:started\n", MODULE_NAME);
return 0;
}

static void demo_exit(void) {
unregister_chrdev
(MAJOR_NUM, "demo");
printk
("<1>%s: removed\n", MODULE_NAME);
}

module_init
(demo_init);
module_exit
(demo_exit);


Compile Kernel Module


make -C /lib/modules/3.8.0-33-generic/build M=`pwd` test.ko


User Space Code


#include <stdio.h>
int main()
{
char buf[512];
FILE
*fp = fopen("/dev/demo", "w+");
if(fp == NULL) {
printf
("can't open device!\n");
return 0;
}
fread
(buf, sizeof(buf), 1, fp);
fwrite
(buf, sizeof(buf), 1, fp);
fclose
(fp);
return 0;
}


Compile User Space Code


gcc test.c


Execute Code


sudo ./a.out


Result


tail -n 10 /var/log/kern.log
Jul 3 12:14:36 happy-Desktop kernel: [12404.120783] device close
Jul 3 12:14:37 happy-Desktop kernel: [12405.044410] device open
Jul 3 12:14:37 happy-Desktop kernel: [12405.044447] device read
Jul 3 12:14:37 happy-Desktop kernel: [12405.044477] device close
Jul 3 12:14:38 happy-Desktop kernel: [12406.056777] device open
Jul 3 12:14:38 happy-Desktop kernel: [12406.056814] device read
Jul 3 12:14:38 happy-Desktop kernel: [12406.056839] device close
Jul 3 12:15:10 happy-Desktop kernel: [12438.189191] device open
Jul 3 12:15:10 happy-Desktop kernel: [12438.189233] device read
Jul 3 12:15:10 happy-Desktop kernel: [12438.189262] device close


[Kernel Module] Make own kernel module

Code 1


#include <linux/init.h> 
#include <linux/module.h> 
MODULE_LICENSE("Dual BSD/GPL"); static char *book_name = "dissecting Linux Device Driver"; static int num = 4000; static int param[8] = {1, 2, 3, 4, 5, 6, 7, 8}; static int param_len = 8; static int book_init(void) { 
    int i; 
    printk(KERN_ALERT " book name: %s\n", book_name); 
    printk(KERN_ALERT " book num: %d\n", num); 
    for(i = 0; i < 8; i++)  
    { 
        printk(KERN_ALERT "param[%d] = %d \n", i, param[i]); 
    } 
    return 0; } 
static void book_exit(void) { 
    printk(KERN_ALERT " Book module exit\n"); } 

module_init(book_init); 
module_exit(book_exit); 
module_param(num, int, S_IRUGO); 
module_param(book_name, charp, S_IRUGO); 
module_param_array(param, int, &param_len, S_IRUGO); 


MODULE_AUTHOR("Jimmy, fightingjimmy@gmail.com"); 
MODULE_DESCRIPTION("A simple Module for testing module params"); 
MODULE_VERSION("v1.0");

Compile


make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
                         |
                         V
make -C /lib/modules/3.8.0-33-generic/build M=`pwd` test.ko

insmod


sudo insmod test.ko book_name='GoodBook' num=5000

Result


Jul  3 07:48:16 happy-Desktop kernel: [10874.385886]  book num: 5000
Jul  3 07:48:16 happy-Desktop kernel: [10874.385891] param[0] = 1 Jul  3 07:48:16 happy-Desktop kernel: [10874.385897] param[1] = 2 Jul  3 07:48:16 happy-Desktop kernel: [10874.385901] param[2] = 3 Jul  3 07:48:16 happy-Desktop kernel: [10874.385933] param[3] = 4 Jul  3 07:48:16 happy-Desktop kernel: [10874.385938] param[4] = 5 Jul  3 07:48:16 happy-Desktop kernel: [10874.385943] param[5] = 6 Jul  3 07:48:16 happy-Desktop kernel: [10874.385947] param[6] = 7 Jul  3 07:48:16 happy-Desktop kernel: [10874.385951] param[7] = 8 

Reference

  1. l​i​n​u​x​ ​模​块​层​叠​技​术​和​多​个​k​o​的​编​译

2014年7月1日 星期二

[Linux Program] Linux System program by example - fork and dup

/* ch09-pipeline.c --- fork two processes into their own pipeline. 
   Minimal error checking for brevity. */  

#include <stdio.h>  
#include <errno.h>  
#include <sys/types.h>  
#include <sys/wait.h>  
#include <unistd.h>  

int pipefd[2];  

extern void left_child(void), right_child(void);  

/* main --- fork children, wait for them to finish */  

int main(int argc, char **argv)  
{  
    pid_t left_pid, right_pid;  
    pid_t ret;  
    int status;  

    if (pipe(pipefd) < 0) {      /* create pipe, very first thing */  
        perror("pipe");  
        exit(1);  
    }  

    if ((left_pid = fork()) < 0) {   /* fork left-hand child */  
        perror("fork");  
        exit(1);  
    } else if (left_pid == 0)  
        left_child();  

    if ((right_pid = fork()) < 0) {  /* fork right-hand child */  
        perror("fork");  
        exit(1);  
    } else if (right_pid == 0)  
        right_child();  

    close(pipefd[0]);       /* close parent's read copy of pipe */  
    close(pipefd[1]);       /* close parent's write copy of pipe */

    while ((ret = wait(& status)) > 0) { /* wait for children */  
        if (ret == left_pid)  /* If left_pid match then ...*/
            printf("left child terminated, status: %x\n", status);  
        else if (ret == right_pid) /* If right_pid match then ...*/  
            printf("right child terminated, status: %x\n", status);  
        else  
            printf("yow! unknown child %d terminated, status %x\n",  
              ret, status);  
    }  

    return 0;  
}  

/* 0 (read)  ---Pipe--> 1 (write) */


/* left_child --- do the work for the left child */  

void left_child(void)  
{  
/* fork - have parent source, so need to close some parameter */
    static char *left_argv[]  = { "echo", "hi", "there", NULL };  

    close(pipefd[0]);  /* Left_child don't need to read */
    close(1);  /* Close standard output */
    dup(pipefd[1]);  /* Copy left_child write to parent's write */
    close(pipefd[1]);  /* Copy parent's write*/ 

    execvp("echo", left_argv);  
    _exit(errno == ENOENT ? 127 : 126);  
}  

/* right_child --- do the work for the right child */  

void right_child(void)  
{  
/* fork - have parent source, so need to close some parameter */    
    static char *right_argv[] = { "sed", "s/hi/hello/g", NULL };  

    close(pipefd[1]);  /* right_child don't need to write */
    close(0);  /* Close standard input */
    dup(pipefd[0]);  
    close(pipefd[0]);  

    execvp("sed", right_argv);  
    _exit(errno == ENOENT ? 127 : 126);  
}  

Reference
1. Linux System programming by example (Example download)

[Linux Program] IPC (Interprocess Communication)




Process




  • Related process - The relation like (parent - Child)

  • unrelated process - Don’t have any relation like (parent - Child)






Method




  • shared memory

  • pipes,FIFOs

  • sockets

  • mapped memory




Pipes


[Related process]

Use (file descriptor) to do IPC




FIFOs (Named Pipe)


[unrelated process]

Use (shared file) to do IPC

2012年10月12日 星期五

[Linux coding][make menuconfig] How to use ext4 filesystem in Embedded system

[Linux coding][make menuconfig] How to use ext4 filesystem in Embedded system

Open ext4 filesystem support

Kernel Configuration  --->

File systems  --->

<*> The Extended 4 (ext4) filesystem

[*]   Use ext4 for ext2/ext3 file systems

[*]   Ext4 extended attributes

[ ]     Ext4 POSIX Access Control Lists

[ ]     Ext4 Security Labels

[ ]   EXT4 debugging support



Q: EXT4-fs (sda): Filesystem with huge files cannot be mounted RDWR without CONFIG_LBDAF

A:

Search LBDAF



Kernel Configuration  --->

[*] Enable the block layer  --->

Support for large (2TB+) block devices and files



Reference :



2012年9月14日 星期五

[GCC library compare] GCC static and share


[GCC library compare] GCC static and share



hello.h



void hello(); 



hello.c



#include <stdio.h>

void hello(){

    printf("hello world\n");

}



main.c



#include <stdio.h>

#include "hello.h"



int main(){

    printf("call hello()");

    hello();

}


 



##############################

Share library

gcc -fPIC -shared hello.c -o libhello.so



gcc main.c -L. -lhello -o main



Q:

./main

./main: error while loading shared libraries: libhello.so: cannot open shared object file: No such file or directory



A:

sudo cp libhello.so /usr/lib/



./main

call hello()hello world



##############################

Static library

gcc -c hello.c -o hello.o



ar -r libhello.a hello.o   # put *.o to *.a. This command like tar.



gcc main.c -lhello -L. -static -o main



./main

call hello()hello world



Reference :




 

2012年6月18日 星期一