1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7. #include <signal.h>
  8. // void func(int sig)
  9. // {
  10. // int ret = -1;
  11. //
  12. // if(sig != SIGIO)
  13. // {
  14. // return ;
  15. // }
  16. // }
  17. int main(int argc, char **argv)
  18. {
  19. int mousefd = -1;
  20. char buf[1024] = {0};
  21. //create two process, one to read mouse, and one to read keyboard
  22. int ret = -1;
  23. ret = fork();
  24. if(ret == 0)
  25. {
  26. //son process
  27. mousefd = open("/dev/input/mouse0", O_RDONLY);
  28. if(mousefd < 0)
  29. {
  30. perror("open");
  31. return -1;
  32. }
  33. while(1)
  34. {
  35. memset(buf, 0, sizeof(buf));
  36. ret = read(mousefd, buf, 1024);
  37. if(ret > 0)
  38. {
  39. printf("context of mouse: [%s]\n", buf);
  40. }
  41. }
  42. }
  43. else if(ret > 0)
  44. {
  45. //parent process
  46. while(1)
  47. {
  48. memset(buf, 0, sizeof(buf));
  49. ret = read(0, buf, 1024); //0 is standard input
  50. if(ret > 0)
  51. {
  52. printf("context of keyboard : [%s]\n", buf);
  53. }
  54. }
  55. }
  56. else
  57. {
  58. perror("fork");
  59. }
  60. return 0;
  61. }

进程技术的缺点:
进程间切换开销大
进程间通信麻烦而且效率低

线程技术保留了进程技术实现多任务的特性
线程的改进就是在线程间切换和线程间通信上提升了效率
多线程在多核心CPU上面更有优势

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7. #include <pthread.h>
  8. char buf[1024] = {0};
  9. void *func()
  10. {
  11. int ret = -1;
  12. while(1)
  13. {
  14. memset(buf, 0, sizeof(buf));
  15. ret = read(0, buf, 1024); //0 is standard input
  16. if(ret > 0)
  17. {
  18. printf("context of keyboard : [%s]\n", buf);
  19. }
  20. }
  21. }
  22. int main(int argc, char **argv)
  23. {
  24. int mousefd = -1;
  25. //create two process, one to read mouse, and one to read keyboard
  26. int ret = -1;
  27. pthread_t th = -1;
  28. ret = pthread_create(&th, NULL, func, NULL);
  29. if(ret != 0)
  30. {
  31. printf("Error: pthread_create");
  32. return -1;
  33. }
  34. //main task
  35. mousefd = open("/dev/input/mouse0", O_RDONLY);
  36. if(mousefd < 0)
  37. {
  38. perror("open");
  39. return -1;
  40. }
  41. while(1)
  42. {
  43. memset(buf, 0, sizeof(buf));
  44. ret = read(mousefd, buf, 1024);
  45. if(ret > 0)
  46. {
  47. printf("context of mouse: [%s]\n", buf);
  48. }
  49. }
  50. return 0;
  51. }

Linux中线程简介

线程是参与内核调度的最小单元
一个进程中可以有多个线程

线程的优势:
像进程一样可被OS调度
同一进程的多个线程之间很容易高效率通信
在多核CPU(对称多处理器架构)架构下效率最大化