#include #include #include #include #include #include #include #include #include #include int main(int argc, char *argv[]) { struct timeval tv1, tv2; gettimeofday(&tv1, NULL); int i; sem_t *sem; key_t shmkey = ftok("./3.c", 24);// change this pathname to whatever you name this file when you save it int shmid = shmget(shmkey, sizeof(sem_t), 0644|IPC_CREAT); if (shmid == -1) { perror("Error creating shared memory"); exit(1); } sem = (sem_t*) shmat(shmid, NULL, 0); sem_init(sem, 1, 5); for (i = 0; i < 10; i++) { int f = fork(); if (f < 0) { perror("Oh no! Anyway..."); } else if (f == 0) { sem_wait(sem); sleep(1); sem_post(sem); exit(0); } } for (i = 0; i < 10; i++) { wait(0); } sem_destroy(sem); shmdt(sem); shmctl(shmid, IPC_RMID, 0); gettimeofday(&tv2, NULL); printf("Total time = %f seconds\n", (double)(tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); return 0; }