pid_alloc.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <sched.h>
  6. #include <sys/time.h>
  7. #include <sys/wait.h>
  8. int func(void* arg) {
  9. return 0;
  10. }
  11. int main(int argc, char** argv) {
  12. for (int i = 0; i < 20; i++) {
  13. int pid = fork();
  14. if (pid < 0) {
  15. printf("fork failed\n");
  16. return -1;
  17. }
  18. if (pid == 0) {
  19. pid = getpid();
  20. struct timeval start_time;
  21. gettimeofday(&start_time, NULL);
  22. for (int j = 0; j < 512; j++) {
  23. void* stack = malloc(4096);
  24. int child =
  25. clone(&func, stack + 4088,
  26. CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_VM | CLONE_SYSVSEM, NULL);
  27. printf("created by %d: %d\n", pid, child);
  28. waitpid(child, NULL, 0);
  29. }
  30. struct timeval finish_time;
  31. gettimeofday(&finish_time, NULL);
  32. printf("time spent: %lu microsecond\n",
  33. (finish_time.tv_sec * 1000000L + finish_time.tv_usec) -
  34. (start_time.tv_sec * 1000000L + start_time.tv_usec));
  35. return 0;
  36. }
  37. }
  38. return 0;
  39. }