I inserted the line sleep(5); to make child sleep for 5 seconds, but after compiling the code it generated the following output:
forkdemo.c:: In function 'main':
forkdemo.c:18:1: error: 'else' without a previous 'if' else.
How can I fix it so that I can make the child sleep without generating an error message after compiling the program?
Also, is the line I inserted to make parent wait for the child to complete its task correct?
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
main()
{
int fork_rv;
printf("Before: my pid is %d\n",getpid());
fork_rv=fork();
if (fork_rv == -1)
perror("fork");
else if (fork_rv == 0)
sleep(5); /* Line I inserted to make child sleep for 5 seconds */
printf ("I am the child. my pid=%d\n",getpid());
else
printf ("I am the parent. my child is %d\n",fork_rv);
wait(NULL); /* line I inserted to make parent wait for child. */
}