Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <signal.h>
- #include <time.h>
- #include <stdbool.h>
- // 6 digits for big triangular numbers like 113050
- #define TRI_BASE 1000000
- // Current process pid (which executed this program)
- pid_t pid;
- // Current process idx (starts from 0)
- int process_idx;
- // Number of triangular numbers found so far
- long tris;
- bool is_triangular(long n) {
- for (long i = 1; i <= n; i++) {
- if (i * (i + 1) == 2 * n) {
- return true;
- }
- }
- return false;
- }
- void signal_handler(int signum) {
- switch (signum) {
- case SIGTSTP:
- // Pause the process indefinitely
- printf("Process %d: stopping....\n", process_idx);
- pause();
- break;
- case SIGCONT:
- // Continue the process
- printf("Process %d: resuming....\n", process_idx);
- break;
- case SIGTERM:
- // Terminate the process
- printf("Process %d: terminating....\n", process_idx);
- exit(EXIT_SUCCESS);
- break;
- default:
- break;
- }
- }
- // Generates a big number n
- long big_n() {
- time_t t;
- long n = 0;
- srand((unsigned)time(&t));
- while (n < TRI_BASE)
- n += rand();
- return n % TRI_BASE;
- }
- int main(int argc, char *argv[]) {
- if (argc != 2) {
- fprintf(stderr, "Usage: %s <process_idx>\n", argv[0]);
- exit(EXIT_FAILURE);
- }
- process_idx = atoi(argv[1]); // Get process_idx from command line argument
- pid = getpid();
- // Register signal handlers
- signal(SIGTSTP, signal_handler);
- signal(SIGCONT, signal_handler);
- signal(SIGTERM, signal_handler);
- long next_n = big_n() + 1;
- printf("Process %d (PID=%d): has been started\n", process_idx, pid);
- printf("Process %d (PID=%d): will find the next triangular number from [%ld, inf)\n", process_idx, pid, next_n);
- // Initialize counter
- tris = 0;
- while (true) {
- if (is_triangular(next_n)) {
- tris++;
- printf("Process %d (PID=%d): I found this triangular number %ld\n", process_idx, pid, next_n);
- }
- next_n++;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement