Skip to content

Instantly share code, notes, and snippets.

@michaellee8
Last active October 4, 2018 01:12
Show Gist options
  • Save michaellee8/89e48d85ac2aba2f27f533c19a51b3c0 to your computer and use it in GitHub Desktop.
Save michaellee8/89e48d85ac2aba2f27f533c19a51b3c0 to your computer and use it in GitHub Desktop.
Inter-process communication using pipes |
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <stdlib.h>
#include <linux/limits.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <signal.h>
#include <stdbool.h>
# define PARENT_TO_CHILD 1
# define CHILD_TO_PARENT 0
# define READ_END 0
# define WRITE_END 1
int main() {
pid_t ppid = getpid();
int n_process = 20;
int n_tasks = 10000;
int n_tasks_per_process = 100;
if (n_process <= 0 || n_tasks <= 0 || n_tasks_per_process <= 0 || n_tasks * n_tasks_per_process < n_tasks) {
return 1;
}
int fds[n_process][2][2];
for (int i = 0; i < n_process; i++) {
pipe(fds[i][CHILD_TO_PARENT]);
pipe(fds[i][PARENT_TO_CHILD]);
}
for (int i = 0; i < n_process; i++) {
if (fork() == 0) {
int num = 1;
while (num != 0) {
read(fds[i][PARENT_TO_CHILD][READ_END], &num, sizeof(int));
printf("Child %d: %d\n", i, num);
int num0 = 0;
write(fds[i][CHILD_TO_PARENT][WRITE_END], &num0, sizeof(int));
}
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
close(fds[i][j][k]);
}
}
}
}
if (ppid == getpid()) {
int num;
int num0 = 0;
for (int i = 1; i <= n_tasks; i++) {
// printf("Requested process %d to do tasks %d\n",
// (i - 1) % (n_process * n_tasks_per_process) / n_tasks_per_process, i);
write(fds[(i - 1) % (n_process * n_tasks_per_process) / n_tasks_per_process][PARENT_TO_CHILD][WRITE_END],
&i,
sizeof(int));
read(fds[(i - 1) % (n_process * n_tasks_per_process) / n_tasks_per_process][CHILD_TO_PARENT][READ_END],
&num,
sizeof(int));
}
for (int i = 0; i < n_process; i++) {
write(fds[i][PARENT_TO_CHILD][WRITE_END], &num0, sizeof(int));
read(fds[i][CHILD_TO_PARENT][READ_END], &num, sizeof(int));
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
close(fds[i][j][k]);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment