public
Created

Pipe and file write test

  • Download Gist
foo.c
C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#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;
}
pipedata.c
C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
#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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.