Skip to content

Instantly share code, notes, and snippets.

@mhluska
Created October 10, 2012 21:09
Show Gist options
  • Save mhluska/3868421 to your computer and use it in GitHub Desktop.
Save mhluska/3868421 to your computer and use it in GitHub Desktop.
Pipe and file write test
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main() {
int c, i;
i = 0;
char buffer[256];
FILE *file;
printf("Reading from stdin.\n");
while ((c = fgetc(stdin)) != EOF) buffer[i++] = c;
buffer[i] = '\0';
if ((file = fopen("file1.txt", "w")) == NULL) {
printf("fopen failed with errno %d", errno);
return 1;
}
fputs(buffer, file);
fclose(file);
return 0;
}
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
FILE *stream;
int fds[2];
int status;
pid_t pid;
char *cmd[] = { "foo", NULL };
pipe(fds);
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
return 1;
}
if (pid > 0) {
// Parent process
close(fds[0]);
stream = fdopen(fds[1], "w");
fprintf(stream, "some string\n");
fflush(stream);
close(fds[1]);
waitpid(pid, &status, 0);
if (WIFEXITED(status) == 0 || WEXITSTATUS(status) < 0)
return 1;
}
else {
// Child process
close(fds[1]);
dup2(fds[0], STDIN_FILENO);
execv("foo", cmd);
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment