c_cpp 一个小样本程序模拟几个工人交替使用fork()和pipe()

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 一个小样本程序模拟几个工人交替使用fork()和pipe()相关的知识,希望对你有一定的参考价值。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

void performTask(int id, int readfd, int writefd) {
	FILE* readFile = fdopen(readfd, "r");
	FILE* writeFile = fdopen(writefd, "w");
	char requestBuffer[100];
	while (fscanf(readFile, "%s", requestBuffer) != EOF) {
		sleep(1);
		fprintf(writeFile, "%d_at_your_service!\n", id);
		fflush(writeFile);
	}
	fclose(readFile);
	fclose(writeFile);
}

int main(int argc, char* argv[]) {
	int nailLength = 0;
	int workerNum = 0;
	sscanf(argv[1], "%d", &nailLength);
	printf("nail length: %d\n", nailLength);
	sscanf(argv[2], "%d", &workerNum);
	printf("number of workers: %d\n", workerNum);

	int** pipes = (int**)malloc(sizeof(int*) * workerNum);
	for (int i = 0; i < workerNum; i++) {
		pipes[i] = (int*)malloc(sizeof(int) * 4);
		pipe(&pipes[i][0]);
		pipe(&pipes[i][2]);

		// pipes[i][0] & pipes[i][1] : pipe from parent to child
		// read from pipes[i][0], write to pipes[i][1]
		// 
		// pipes[i][2] & pipes[i][3] : pipe from child to parent
		// read from pipes[i][2], write to pipes[i][3]

		int forkResult = fork();
		if (forkResult == 0) {
			close(pipes[i][1]);
			close(pipes[i][2]);
			performTask(i, pipes[i][0], pipes[i][3]);
			return 0;
		}
		else {
			close(pipes[i][0]);
			close(pipes[i][3]);
		}
	}

	FILE** readFiles = (FILE**)malloc(sizeof(FILE*) * workerNum);
	FILE** writeFiles = (FILE**)malloc(sizeof(FILE*) * workerNum);
	for (int i = 0; i < workerNum; i++) {
		readFiles[i] = fdopen(pipes[i][2], "r");
		writeFiles[i] = fdopen(pipes[i][1], "w");
	}

	srand(time(0));
	char responseBuffer[100];
	for (int i = 0; i < nailLength; i++) {
		sleep(1);
		int workerChosen = rand() % workerNum;
		printf("Do it, #%d!\n", workerChosen);
		fprintf(writeFiles[workerChosen], "#%d_do_it!\n", workerChosen);
		fflush(writeFiles[workerChosen]);
		fscanf(readFiles[workerChosen], "%s", responseBuffer);
		printf("%s\n", responseBuffer);
	}

	for (int i = 0; i < workerNum; i++) {
		fclose(readFiles[i]);
		fclose(writeFiles[i]);
	}

	return 0;
}

以上是关于c_cpp 一个小样本程序模拟几个工人交替使用fork()和pipe()的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 交替拆分给定的单链表

朴素贝叶斯分类器

c_cpp CV - 使用随机样本共识(RANSAC)匹配图像。

工人、工人实例和执行者之间的关系是啥?

如何使用 PyTorch 的 DataLoader 确保批次包含来自所有工作人员的样本?

c_cpp dlib图样本