-1

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. */
}
Arda Aytekin
  • 1,231
  • 14
  • 24
Anon
  • 33
  • 5
  • 2
    You need a few [good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) to read. You have a very basic error that no good (or bad for that matter) book or tutorial or course would have taught you. – Some programmer dude Mar 03 '18 at 23:12
  • 2
    Never mind the forking and sleeping, just try to write `if...else if...else...` correctly. If you can't get that to work, try `if...else...`. If you can't get that to work, just try `if...`. **Simplify.** – Beta Mar 03 '18 at 23:14

1 Answers1

2

You should use blaces {} to build a block from multiple statements for use in if statement (and others like for).

Try this:

#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. */
    }
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70