Reputation: 497
I have the following block of code :
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "display.h"
int main()
{
int i;
if (fork())
{
for (i=0;i<10;i++)
display("ab");
wait(NULL);
}
else
{
for (i=0;i<10;i++)
display("cd\n");
}
return 0;
}
Where display.c is :
/* DO NOT EDIT THIS FILE!!! */
#include <stdio.h>
#include <unistd.h>
#include "display.h"
void display(char *str)
{
char *p;
for (p=str; *p; p++)
{
write(1, p, 1);
usleep(100);
}
}
and display.h is :
/* DO NOT EDIT THIS FILE!!! */
#ifndef __CEID_OS_DISPLAY_H__
#define __CEID_OS_DISPLAY_H__
void display(char *);
#endif
If i run this code the output is :
abacdb
abcdab
acdbababa
cbadb
cad
bcd
cd
cd
cd
cd
I want to use semaphores in order to have an output like this :
abcd
abcd
abcd
....
My attempt to do this is the following :
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/wait.h>
#include "display.h"
#include <semaphore.h>
#include <stdio.h>
int main()
{
int i, my_sem, v1,v2,t;
my_sem = semget(IPC_PRIVATE, 1, 0600); /* CREATE OF THE SEMAPHORES */
struct sembuf up = {0, 1, 0};
struct sembuf down = {0, -1, 0};
if (fork())
{
for (i=0;i<10;i++){
display("ab");
semop(my_sem, &up, 1); /* UP (); */
wait(NULL);
}
}
else
{
for (i=0;i<10;i++){
semop(my_sem, &down, 1); /* DOWN (); */
display("cd\n");
semop(my_sem, &up, 1); /* UP (); */
}
}
return 0;
}
The output of my code is :
abcd
cd
cd
cd
cd
cd
cd
cd
cd
cd
ababababababababab
It seems that it works only for the first time. I am very new into sempaphores so i need some help in order to make my code work.
Thank you for your time.
Upvotes: 4
Views: 3004
Reputation: 250
wait(null)
waits for the child process to terminate, in this case you're waiting for the child to completely finish before resuming your "ab" loop, hence why "ab" is displayed once followed by all "cd" lines.
You need to think further about how to communicate between processes. You can use your semaphores (their values) to prevent one process from making progress while allowing another to make progress.
Upvotes: 3