Advertisement
teknoraver

linux threading

Nov 5th, 2015
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.32 KB | None | 0 0
  1. #define _GNU_SOURCE
  2.  
  3. #include <stdio.h>  /* printf */
  4. #include <unistd.h> /* open, read, fork */
  5. #include <stdlib.h> /* malloc, exit */
  6. #include <stdint.h> /* uint_32_t */
  7. #include <string.h> /* strcmp, memcpy */
  8. #include <pthread.h>
  9. #include <sched.h>
  10.  
  11. void * pthread_func(void *arg)
  12. {
  13.     printf("%s\n", __FUNCTION__);
  14.  
  15.     while(1)
  16.         sleep(10);
  17.  
  18.     return (void *)0;
  19. }
  20.  
  21. int clone_func(void *arg)
  22. {
  23.     printf("%s\n", __FUNCTION__);
  24.  
  25.     while(1)
  26.         sleep(10);
  27.  
  28.     return 0;
  29. }
  30.  
  31. void fork_func(void)
  32. {
  33.     if(!fork()) {
  34.         printf("%s\n", __FUNCTION__);
  35.         while(1)
  36.             sleep(10);
  37.     }
  38. }
  39.  
  40. void usage(char *argv0)
  41. {
  42.     printf("usage: %s [-tclf]\n", argv0);
  43.     exit(0);
  44. }
  45.  
  46. #define STACK_SIZE 4096
  47.  
  48. int main(int argc, char *argv[])
  49. {
  50.     char *stack = malloc(STACK_SIZE);
  51.     pthread_t pt;
  52.  
  53.     if(argc != 2 || strlen(argv[1]) != 2 || argv[1][0] != '-')
  54.         usage(argv[0]);
  55.     switch(argv[1][1]) {
  56.     case 't':
  57.         pthread_create(&pt, NULL, pthread_func, 0);
  58.         break;
  59.     case 'c':
  60.         clone(clone_func, stack + STACK_SIZE, 0, 0);
  61.         break;
  62.     case 'l':
  63.         clone(clone_func, stack + STACK_SIZE,
  64.               CLONE_FILES | CLONE_FS | CLONE_IO | CLONE_PARENT |
  65.               CLONE_SIGHAND | CLONE_SYSVSEM | CLONE_THREAD | CLONE_VM, 0);
  66.         break;
  67.     case 'f':
  68.         fork_func();
  69.         break;
  70.     default:
  71.         usage(argv[0]);
  72.     }
  73.  
  74.     while(1)
  75.         sleep(10);
  76.  
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement