如何修改这个程序让孩子睡5秒?

问题描述 投票:-1回答:1

我插入了行睡眠(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. */
}
c
1个回答
2
投票

您应该使用刀片qazxsw poi从多个语句构建一个块,以便在qazxsw poi语句中使用(以及其他类似{})。

试试这个:

if
© www.soinside.com 2019 - 2024. All rights reserved.