Skip to content

Instantly share code, notes, and snippets.

@trnila
Created February 29, 2016 22:51
Show Gist options
  • Save trnila/882c3beb9c77c947ab3c to your computer and use it in GitHub Desktop.
Save trnila/882c3beb9c77c947ab3c to your computer and use it in GitHub Desktop.
fork
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
int main() {
int mypipe[2];
pipe(mypipe);
int r = fork();
if(r == -1) {
perror("Fork failed");
exit(1);
} else if(r == 0) {
printf("child pid: %d\n", getpid());
close(mypipe[0]);
char buffer[100];
for(int i = 0; i < 100; i++) {
sprintf(buffer, "%d;", i);
write(mypipe[1], buffer, strlen(buffer));
}
close(mypipe[1]);
printf("child ends\n");
} else {
printf("Master process\n");
close(mypipe[1]);
int sum = 0;
char buffer[100];
ssize_t bytesRead;
ssize_t offset = 0;
while((bytesRead = read(mypipe[0], buffer + offset, sizeof(buffer) - 1 - offset)) != 0) {
buffer[offset + bytesRead + 1] = 0;
// parse numbers in string
int pos = 0, bytesScanned = 0;
int num;
char c = 0;
while(sscanf(buffer + pos, "%d%c%n", &num, &c, &bytesScanned) == 2) {
if(c != ';') {
break;
}
pos += bytesScanned;
sum += num;
}
ssize_t remaining = bytesRead - pos;
// copy not processed bytes to the beginning
offset = 0;
if(remaining > 0) {
strcpy(buffer, buffer + pos);
offset = remaining;
}
}
printf("Master ends with sum: %d\n", sum);
wait(NULL);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment