Reputation:
This program gets a sentence in parent process and prints it in upper case in child process. I want the child to wait for the parent. I used sleep() to make the child process to wait. Is there any method of making a child to wait for the parent ? Can i implement that with signal() ? Thanks in advance!!!
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<ctype.h>
#define size 50
main()
{
int pid,shmid,i,key=1234;
char *name,*shmaddr;
if((shmid=shmget(key,size,IPC_CREAT | 0666)) < 0)
{
perror("shmget():");
exit(1);
}
pid=fork();
if(pid < 0)
{
perror("fork():");
exit(1);
}
else if(pid == 0)
{
sleep(5); //making child to wait for parent
printf("\t\tCHILD\n\n");
if((shmaddr=shmat(shmid,NULL,0)) == (char*) -1)
{
perror("shmat():");
exit(1);
}
name=shmaddr;
i=0;
while(name[i]!='\0')
{
printf("%c",toupper(name[i]));
i++;
}
shmdt(shmaddr);
printf("\n");
exit(0);
}
else
{
printf("\t\tPARENT\n\n");
if((shmaddr=shmat(shmid,NULL,0)) == (char*) -1)
{
perror("shmat():");
exit(1);
}
name=shmaddr;
i=0;
while((name[i]=getchar()) != '\n')
i++;
name[i]='\0';
shmdt(shmaddr);
wait(NULL);
}
}
Upvotes: 2
Views: 4065
Reputation: 212258
The simplest way to have the child wait is to use a pipe. The child blocks on a read, and then then the parent writes a single byte into the pipe when it is done writing into shared memory. The child will proceed past the read only when it consumes that byte. (Of course, in this simple scenario, there is no need for shared memory, since the parent can simply write the data into the pipe instead of into shared memory!)
Upvotes: 2