#include #include #include #include #include #include #include #include #include #include #include #define COUNT 100 #define MAX_PROCS 2048 #define MAX_ITERATIONS 2048 #define SHM_FAILED ((void *) -1) #define NBPG 4096 char wbuf[4096]; int *g_mstart; void run_test(char *base, int count) { char pbuf[1024]; int fd, i, j; sprintf(pbuf, "%s/file-%d", base, count); fd = open(pbuf, O_CREAT | O_TRUNC | O_WRONLY, 0644); if (fd < 0) { perror("open"); exit(1); } for (i = 0; i < COUNT; i++) { if (pwrite(fd, wbuf, 4096, 0) != 4096) { perror("pwrite"); exit(1); } for (j = 4095; j >= 1; j--) { if (ftruncate(fd, j) < 0) { perror("ftruncate"); exit(1); } } } } int run_main(int procs, char *basedir) { int i, j; pid_t pids[MAX_PROCS]; clock_t start_clock; struct tms start_times; clock_t end_clock; struct tms end_times; while (!*g_mstart); start_clock = times(&start_times); for (i = 0; i < procs; i++) { pids[i] = fork(); if (pids[i] < 0) { perror("fork"); for (j = 0; j < i; j++) kill(pids[j], SIGKILL); return 1; } if (pids[i] == 0) { run_test(basedir, i); exit(0); } } #ifdef PRINT_TIMES printf("Processes started for %s.\n", basedir); #endif /* PRINT_TIMES */ for (i = 0; i < procs; i++) waitpid(pids[i], NULL, 0); end_clock = times(&end_times); #ifdef PRINT_TIMES printf("Real Time: %jd User Time %jd System Time %jd.\n", (intmax_t)(end_clock - start_clock), (intmax_t)(end_times.tms_utime - start_times.tms_utime), (intmax_t)(end_times.tms_stime - start_times.tms_stime)); fflush(stdout); #endif /* PRINT_TIMES */ return 0; } int main(int argc, char **argv) { int procs, i, j; pid_t mpids[MAX_ITERATIONS]; int niterations = 10; char basedir[64]; int n, shmid; if (argc < 3) { fprintf(stderr, "Usage: stress-orphan " " []\n"); return 1; } if (argc > 3) { niterations = atoi(argv[3]); if (niterations > MAX_ITERATIONS) { fprintf(stderr, "Warning: iterations %d > " " MAX %d.\n", niterations, MAX_ITERATIONS); niterations = MAX_ITERATIONS; } } if ((shmid = shmget(IPC_PRIVATE, NBPG, 0600)) < 0) { fprintf(stderr, "Error in shmget, errno %d.\n", errno); return 1; } if ((g_mstart = (int *)shmat(shmid, 0, 0)) == SHM_FAILED) { fprintf(stderr, "Error in shmat, errno %d.\n", errno); return 1; } *g_mstart = 0; procs = strtol(argv[1], NULL, 10); if (procs > MAX_PROCS) { fprintf(stderr, "Too many processes!\n"); return 1; } strcpy(basedir, argv[2]); n = strlen(basedir); for ( i = 0 ; i < niterations ; i++ ) { sprintf(&basedir[n], "%d", i + 1); mpids[i] = fork(); if (mpids[i] < 0) { perror("fork"); for (j = 0; j < i; j++) kill(mpids[j], SIGKILL); return 1; } if (mpids[i] == 0) { run_main(procs, basedir); exit(0); } } printf("Main started for %d %s %d.\n", procs, basedir, niterations); *g_mstart = 1; for (i = 0; i < niterations ; i++) waitpid(mpids[i], NULL, 0); printf("Main Processes Done.\n"); }