You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

48 lines
1.0 KiB

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <time.h>
  5. #include <sys/types.h>
  6. #include <sys/wait.h>
  7. int main() {
  8. srand(time(NULL));
  9. FILE *out = fopen("temp.txt", "w");
  10. int u[120], v[120];
  11. for (int i = 0; i < 120; ++i)
  12. u[i] = rand() % 100, v[i] = rand() % 100;
  13. int n;
  14. scanf("%d", &n);
  15. pid_t id[10];
  16. int start = -1, sz = 120 / n;
  17. for (int i = 0; i < n; ++i) {
  18. id[i] = fork();
  19. if (id[i] == 0) {
  20. start = i * sz;
  21. break;
  22. }
  23. }
  24. if (start != -1) {
  25. int res = 0;
  26. for (int i = 0; i < sz; ++i) {
  27. res += u[start + i] * v[start + i];
  28. }
  29. fprintf(out, "%d\n", res);
  30. } else {
  31. int status;
  32. wait(&status);
  33. fclose(out);
  34. int res = 0;
  35. FILE *in = fopen("temp.txt", "r");
  36. for (int i = 0; i < n; ++i) {
  37. int a;
  38. fscanf(in, "%d", &a);
  39. res += a;
  40. }
  41. fclose(in);
  42. printf("Result: %d\n", res);
  43. }
  44. }