Skip to content

Instantly share code, notes, and snippets.

@nmreadelf
Last active March 30, 2023 04:40
Show Gist options
  • Save nmreadelf/86ebce01ab12cae227964e4428ed3eef to your computer and use it in GitHub Desktop.
Save nmreadelf/86ebce01ab12cae227964e4428ed3eef to your computer and use it in GitHub Desktop.
prime multi process
#include <stdio.h>
#include <stdlib.h>
#define MAX 35
int
generate() {
int p[2];
pipe(p);
for (int i = 2; i < MAX; i++) {
write(p[1], &i, sizeof(i));
}
close(p[1]);
return p[0];
}
int
filter(int in_fd, int prime) {
int num;
int p[2];
pipe(p);
int pid = fork();
if (pid > 0) {
close(2);
close(1);
while (read(in_fd, &num, sizeof(num))) {
if (num % prime) {
write(p[1], &num, sizeof(num));
}
}
close(in_fd);
close(p[1]);
wait((int *)0);
exit(0);
}
close(in_fd);
close(p[1]);
return p[0];
}
int
main(int argc, char *argv[])
{
close(0);
int prime;
int in = generate();
while (read(in, &prime, sizeof(prime))) {
printf("prime %d\n", prime);
in = filter(in, prime);
}
wait((int *)0);
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment