Skip to content

Instantly share code, notes, and snippets.

@yyoncho
Last active December 7, 2021 08:10
Show Gist options
  • Select an option

  • Save yyoncho/9ca85797d8588f684bdc7176784f5bbf to your computer and use it in GitHub Desktop.

Select an option

Save yyoncho/9ca85797d8588f684bdc7176784f5bbf to your computer and use it in GitHub Desktop.
int main(void) {
int pfd[2]; /* Pipe’s file descriptors. */
pid_t child_pid; /* Child’s process id. */
/* Set up pipe. */
if (pipe(pfd) == -1) {
fprintf(stderr, "Call to pipe failed.\n");
exit(1);
}
/* FILE *out = fdopen(pfd[1], "a"); */
/* Fork a child process and let it execute the grep command. */
if ((child_pid = fork()) == 0) {
/* The child process. First, redirect its stdout to pipe. */
if (dup2(pfd[1], STDOUT_FILENO) == -1) {
fprintf(stderr, "dup2 in child failed.\n");
exit(1);
}
if (dup2(pfd[0], STDIN_FILENO) == -1) {
fprintf(stderr, "dup2 in child failed.\n");
exit(1);
}
/* Now that redirection of stdout to pipe has been accomplished, */
/* remove the file descriptors for the pipe from the child’s */
/* file descriptor table. */
if (close(pfd[0]) == -1) { /* Failed to close read end of pipe. */
fprintf(stderr, "Couldn’t close read end of pipe in child\n");
exit(1);
}
if (close(pfd[1]) == -1) { /* Failed to close write end of pipe. */
fprintf(stderr, "Couldn’t close write end of pipe in child\n");
exit(1);
}
/* Exec the grep command. */
execlp("cat", "cat",
"/home/yyoncho/Sources/nim/jsonrpc/test/fixtures/message.txt", NULL);
/* If the following statement is reached, execlp must have failed. */
/* close(int __fd) */
/* fprintf(stderr, "Call to execlp in child failed.\n"); */
exit(1);
} /* End of child. */
else {
/* The parent process. Make sure that fork worked. */
if (child_pid == (pid_t)-1) {
fprintf(stderr, "The call to fork failed.\n");
exit(1);
}
printf("XX");
char *line;
size_t len;
FILE *in = fdopen(pfd[0], "r");
/* FILE *fp = pfd[0]; */
int header_len = strlen("Content-Length:");
printf("XX");
while ((getline(&line, &len, in) != -1)) {
char *end;
if (!strncmp(line, "Content-Length:", header_len)) {
size_t message_lenght = strtol(line + header_len, &end, 36);
char *buf = (char *)malloc(message_lenght);
/* printf(">> message_lenght = %d\n", message_lenght); */
// skip new lines after the header
while ((getline(&line, &len, in) != -1) && (strcmp(line, "\r\n") != 0))
;
/* read(; */
int res = fread(buf, 8, 1, in);
printf(">> res = |%d|\n", res);
printf(">> buf = |%s|\n", buf);
int c = fgetc(in);
printf(">>>>>>> XXXXX\n");
if (c == EOF) {
break;
} else {
printf(">>>>>>> %d\n", c);
ungetc(c, in);
}
/* free(buf); */
}
}
/* pclose(in); */
} /* End of parent. */
return 0;
} /* End of main. */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment