pid_alloc.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #define __USE_GNU
  7. #include <sched.h>
  8. #include <sys/wait.h>
  9. #include <sys/time.h>
  10. int func (void *arg)
  11. {
  12. return 0;
  13. }
  14. int main(int argc, char ** argv)
  15. {
  16. for (int i = 0 ; i < 20 ; i++) {
  17. int pid = fork();
  18. if (pid < 0) {
  19. printf("fork failed\n");
  20. return -1;
  21. }
  22. if (pid == 0) {
  23. pid = getpid();
  24. struct timeval start_time;
  25. gettimeofday(&start_time, NULL);
  26. for (int j = 0 ; j < 512 ; j++) {
  27. void * stack = malloc(4096);
  28. int child = clone(&func, stack + 4088,
  29. CLONE_FS|CLONE_FILES|CLONE_SIGHAND|
  30. CLONE_VM|CLONE_SYSVSEM,
  31. NULL);
  32. printf("created by %d: %d\n", pid, child);
  33. waitpid(child, NULL, 0);
  34. }
  35. struct timeval finish_time;
  36. gettimeofday(&finish_time, NULL);
  37. printf("time spent: %lu microsecond\n",
  38. (finish_time.tv_sec * 1000000L + finish_time.tv_usec)
  39. - (start_time.tv_sec * 1000000L + start_time.tv_usec));
  40. return 0;
  41. }
  42. }
  43. return 0;
  44. }