<分区>
我是 C 的新手,所以我只知道简单的函数。(例如:wait(NULL))。
这是我的主要问题:
Modify the program so that only the parent process creates 3 child processes, and each new created process calls a function CPU(). In addition, make the parent process wait for each child’s termination.
我知道这个是正确答案
#include<stdio.h>
int main(void)
{
int i ;
for( i = 0; i < 3; i++)
{
int ret = fork();
if(ret == 0){
printf("My process ID is %d\n", getpid());
return 0;
}
}
for (i = 0; i < 3; i++) //Line B
wait(NULL);
}
但我的问题是
为什么wait在循环中被parent执行时下面的代码是错误的
#include <stdio.h> int main(void) { int i ; for( i = 0; i < 3; i++) { int ret = fork(); if(ret == 0) { printf("My process ID is %d\n", getpid()); return 0; } else wait(NULL); } }
在最开始的代码中,为什么我们要在 for 循环中编写
wait(NULL)
? 我们不能不使用 for 循环来写吗如果子进程中没有“return 0”,for循环是否应该改为
for (i = 0; i <7; i++) wait(NULL);
我不会写
CPU
函数