Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <signal.h>
  6. #include <sys/types.h>
  7.  
  8. char cmdbuf[128] = "echo interrupt signal caught, terminating ";
  9. char *progname;
  10.  
  11. /*
  12. * Handle interrupt in case the program is running
  13. * too long and the user wants to terminate it.
  14. */
  15. void handle_signal(int sig)
  16. {
  17. int len = sizeof(cmdbuf) - (strlen(cmdbuf) + 1);
  18. if (strlen(progname) > len)
  19. progname[len] = '\0';
  20. strcat(cmdbuf, progname);
  21.  
  22. system(cmdbuf);
  23. exit(1);
  24. }
  25.  
  26. void usage()
  27. {
  28. printf("%s <n> where 0 < n <= 5.000\n", progname);
  29. exit(1);
  30. }
  31.  
  32. /*
  33. * The program takes one argument line parameter n (which has to be a
  34. * positive integer input parameter) and then prints out the first n
  35. * prime numbers.
  36. */
  37. int main(int argc, char **argv)
  38. {
  39. struct sigaction sa;
  40. int cnt, N, found;
  41. unsigned long candidate, divisor;
  42.  
  43. gid_t egid = getegid();
  44. setregid(egid, egid);
  45.  
  46. /* set up signal handling */
  47. memset(&sa, sizeof(struct sigaction), 0);
  48. sa.sa_handler = handle_signal;
  49. sigaction(SIGUSR1, &sa, NULL);
  50.  
  51.  
  52. /* process argument */
  53. progname = argv[0];
  54. if (argc != 2)
  55. usage();
  56. N = strtol(argv[1], NULL, 10);
  57. if ((N <= 0) || (N > 50000000))
  58. usage();
  59.  
  60.  
  61. /* calculate prime numbers -- simple sieve */
  62. candidate = 1;
  63. for (cnt = 0; cnt < N; ++cnt) {
  64.  
  65. for (;;) {
  66. found = 1;
  67. divisor = 2;
  68. candidate += 1;
  69.  
  70. while (divisor <= candidate/2) {
  71. if ((candidate % divisor) == 0) {
  72. found = 0;
  73. break;
  74. }
  75. else
  76. ++divisor;
  77. }
  78. if (found)
  79. break;
  80. }
  81. printf("%ld\n", candidate);
  82. }
  83.  
  84. return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement