我真的被这项任务卡住了。这是一个我必须用C语言编写的非常简单的程序,其目的是演示fork()和wait()的用法。
指令上写着“在终止前执行15次迭代。在每次迭代中,程序将创建10个子进程(从p0到p9)。每个进程在退出前都会打印一次十进制数字,没有换行符。在创建10个子进程之后,父进程将等待它的10个子进程完成,然后在进入下一次迭代或退出之前打印一个换行符。不要对fork()进行10次显式调用,只使用一个带有fork()调用实例的循环。为了等待所有子进程完成,在循环中使用wait(NULL),直到wait(NULL)的返回值为-1。“
以下是示例输出:
9856724310
8149765320
2789654310
0139874265
8765320149
2145367809
0123456798
0124356789
0123546789
9854320761
0123678594
0142685379
0123456789
6795438210
2394567081这是我所拥有的,但似乎我尝试的每一种方法,数字都是按顺序打印的,没有任何不可预测性。
#include <cstdlib>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
using namespace std;
int main(int argc, char** argv) {
pid_t pid;
for(int i=0; i<15; i++){
//fork();
for(int j=0; j<10; j++){
pid = fork();
printf("%d", j);
}
wait(NULL);
printf("\n");
}
return 0;
}任何帮助都是非常感谢的!谢谢!
发布于 2019-02-21 03:53:17
你理解错了。在fork()上,您可以想象fork()之后的代码同时执行,两个进程共享相同的代码(因为内存是复制的)。区分父进程和子进程的方法是通过if-子句,因为fork()为每个进程返回不同的值。如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void) {
for (int i=0; i<15; i++){
for(int j=0; j<10; j++){
if (fork()==0){
//child process return 0 from fork()
printf("%d", j);
exit(0);
}
else{
//parent process return pid of the forked process from fork()
continue;
}
}
while (wait(NULL)!=-1);//wait for all child processes. wait() only return -1 when no more children to wait for
printf("\n");
}
return 0;
}发布于 2019-02-21 04:01:05
您需要区分要在父进程或子进程中运行的代码(现在您在两个进程上运行相同的代码)。这可以通过fork()的返回值来完成,因为fork将子进程的pid返回子进程,并将0返回子进程。因此,您可以实现如下检查:
pid = fork();
if (pid == 0) {
//Code for child process
exit(0);
}
//Code for parent process发布于 2019-02-21 04:03:21
无论何时使用子进程,始终要区分父代码和子代码。子进程通过具有pid=0来标识,而父进程将根据pid在执行时具有的pid > 0来标识。此外,如果在派生一个子进程时发生错误,那么fork将返回值<0,因此您应该考虑这种情况。
在你的代码中没有这样的东西。最经典的方法是这样做:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
pid_t pid;
for(int i=0;i<15;i++){
for(int j=0; j<10; j++){
if((pid = fork())<0){
perror("Fork Failed.");
exit(EXIT_FAILURE);
}
if(pid==0){ /*Child Code here*/
printf("%d", j);
exit(EXIT_SUCCESS);
}
}
while(wait(NULL)!=-1); //while loop to wait
printf("\n");
}
return 0;
}https://stackoverflow.com/questions/54793571
复制相似问题