fork download
  1. #include <mpi.h> // Include the MPI library for communication
  2. #include <stdio.h> // For input and output
  3. #include <stdlib.h> // For random number generation
  4.  
  5. int main(int argc, char **argv) {
  6. int rank, size; // Rank of the current process and total number of processes
  7. char report[50]; // Buffer for the treasure report
  8. MPI_Status status; // Variable to hold the status of communication
  9.  
  10. MPI_Init(&argc, &argv); // Initialize the MPI environment
  11. MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Get the rank of the current process
  12. MPI_Comm_size(MPI_COMM_WORLD, &size); // Get the total number of processes
  13.  
  14. if (rank == 0) {
  15. // Process 0: John Silver
  16. printf("John Silver is waiting for reports from %d groups of pirates...\n", size - 1);
  17.  
  18. for (int i = 1; i < size; i++) {
  19. // Receive reports from all other processes
  20. MPI_Recv(report, 50, MPI_CHAR, i, 0, MPI_COMM_WORLD, &status);
  21. printf("Report from group %d: %s\n", i, report);
  22. }
  23.  
  24. printf("All reports received. John Silver can now plan his next move.\n");
  25.  
  26. } else {
  27. // Other processes: Pirate groups
  28. srand(rank); // Seed the random number generator with the process rank
  29. int found_treasure = rand() % 2; // Randomly decide if treasure is found (0 or 1)
  30.  
  31. // Create the report
  32. if (found_treasure) {
  33. sprintf(report, "Found treasure in section %d!", rank);
  34. } else {
  35. sprintf(report, "No treasure in section %d.", rank);
  36. }
  37.  
  38. // Send the report to John Silver (process 0)
  39. MPI_Send(report, 50, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
  40. }
  41.  
  42. MPI_Finalize(); // Clean up the MPI environment
  43. return 0;
  44. }
  45.  
Success #stdin #stdout #stderr 0.29s 40768KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "int main"
Execution halted