[英]How to modify this program to make child sleep for 5 seconds?
我插入了sleep(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. */
}
您應該使用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. */
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.