我插入了行睡眠(5);让孩子睡5秒,但在编译代码后,它产生了以下输出:
forkdemo.c:: In function 'main':
forkdemo.c:18:1: error: 'else' without a previous 'if' else.
如何修复它以便在编译程序后让孩子睡眠而不会产生错误信息?
另外,我插入的行是为了让父母等待孩子完成其任务正确吗?
#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. */
}
答案 0 :(得分:2)
您应该使用blaces {}
从多个语句构建一个块,以便在if
语句中使用(以及其他类似for
)。
试试这个:
#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. */
}
}