How to synchronize processes in C

Mathilda100
Mathilda100 used Ask the Experts™
on
Hello everyone,
I am trying to create a C program that will synchronize parent and child processes and will print out following:

I am child, my iteration is 1
I am parent, my iteration is 1
I am child, my iteration is 2
I am parent, my iteration is 2

However, the code I have made so far prints out the following:
I am child, my iteration is 1
I am child, my iteration is 2
I am parent, my iteration is 1
I am parent, my iteration is 2

I think the problem with my code is that I am using wait((int *)0);  which makes the parent wait for the child to finish it’s process first.  Can someone point me to a right track?
Below is my code

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

int main()
{
int i;
pid_t pid;
pid = fork();
switch(pid)
{
case -1: /* an error occurred */
printf("There is a fork error");
break;
case 0: /* child process */
for(i=1; i<3; i++)
printf("I am child, my iteration: %d\n", i);
 _exit(0);

break;
default: /* parent process */
wait((int *)0); 

for(i=1; i<3; i++)
printf("I am parent, my iteration: %d\n", i);
}
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Senior Software Engineer (Avast)
Commented:
You'll need to use a named semaphore.
http://linux.die.net/man/7/sem_overview

Author

Commented:
Thank you Elvirix for the link. I need to study the named semaphores a little bit more I have never heard of them, therefore, have never used them.
Commented:
You can use pause() and kill() to exchange signals.
if (isParent)
    pause()
    print
    kill(childPID, signalNumber)
else
    print
    kill(parentPID, signalNumber)
    pause()

Just carefully select the signalNumber and probably set its handler.

Author

Commented:
Thank you Evilrix for pointing me to the right direction. I have learned a lot about semaphores, and that helped me to solve my issue with the program.
Thank you also Jiexa for your suggestion of using signals; looks like there are several ways how to solve the issues.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial