c - Unexpected Output Running Semaphore -
this question exact duplicate of:
- unexpected output running semaphore 1 answer
the first process shouldn't start (i)th iteration unless second process has finished (i-1)th iteration.the output not need.i wonder if possible have output 2 semaphores? here code.
#include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <semaphore.h> sem_t sema, semb,sem,m; int main(void) { int i; pid_t child_a, child_b,pid2,pid3; sem_init(&sema, 0, 1); sem_init(&semb, 0, 0); sem_init(&m, 0, 0); child_a = fork(); //wait(); if (child_a == 0) { // int j; pid2 =getpid(); (i = 0; < 5; ) { sem_wait(&sema); //sem_wait(&m); printf("child1: %d\n", i); i++; //printf("pid1: %d\n", pid2); //printf("--------------------------\n"); sleep(3); //sem_post(&m); sem_post(&semb); } } else { child_b = fork(); //wait(); if (child_b == 0) { pid3 =getpid(); (i = 0; < 5;) { sem_wait(&semb); //sem_wait(&m); printf("child2: %d\n", i); i++; //printf("pid2: %d\n", pid3); //printf("--------------------------\n"); sleep(5); //sem_post(&m); sem_post(&sema); } } } exit(0); return 0; }
the output expect is:
child1: 0 child2: 0 child1: 1 child2: 1 child1: 2 child2: 2 child1: 3 child2: 3 child1: 4 child2: 4 child1: 5 child2: 5 child1: 6 child2: 6 child1: 7 child2: 7 child1: 8 child2: 8 child1: 9 child2: 9
but 1 child:
child1: 0
(i'm running ubuntu 12.10)
in order use semaphores across multiple processes, have either use named semaphores or place semaphores in shared memory.
see linux man page sem_overview(7).
for doing, named semaphores easier use shared memory. following should work:
#include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <semaphore.h> #include <fcntl.h> #include <sys/stat.h> sem_t * sema; sem_t * semb; int main(void) { int i; pid_t child_a, child_b,pid2,pid3; sema = sem_open("/mysema", o_creat, s_irusr | s_iwusr, 1); semb = sem_open("/mysemb", o_creat, s_irusr | s_iwusr, 0); child_a = fork(); if (child_a == 0) { pid2 =getpid(); (i = 0; < 5; ) { sem_wait(sema); printf("child1: %d\n", i); i++; sem_post(semb); sleep(3); } } else { child_b = fork(); if (child_b == 0) { pid3 =getpid(); (i = 0; < 5;) { sem_wait(semb); printf("child2: %d\n", i); i++; sleep(5); sem_post(sema); } } } exit(0); return 0; }
Comments
Post a Comment