Mr.Pytagoras
December 8th, 2011, 05:20 PM
Hi
I'm writing a program which use fork() and I need to read output from child process in parent process
That I did like this:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <errno.h>
int main(void)
{
int pipefd1[2], pipefd2[2], pipefd3[2];
pid_t pid1, pid2, pid3, wait_pid;
int status;
int i;
int pipefd[2];
if(pipe(pipefd1) == -1){
fprintf(stderr, "Error: %s\n", strerror(errno));
exit (EXIT_FAILURE);
}
char buffer[1024];
switch(pid1 = fork()){
case -1: //fail
fprintf(stderr, "Error: fork 1\n");
exit(1);
case 0: //potomok
close(pipefd1[0]);
dup2(pipefd1[1], 1);
dup2(pipefd1[1], 2);
close(pipefd1[1]);
fprintf(stdout ,"1. from forked child number: 1\n");
fprintf(stdout ,"2. from forked child number: 1\n");
fprintf(stdout ,"3. from forked child number: 1\n");
exit(0);
break;
default:
close(pipefd1[1]); // close the write end of the pipe in the parent
while (read(pipefd1[0], buffer, sizeof(buffer)) > 0){
printf("%s", buffer);
}
}
wait_pid = wait(&status);
printf("process: %d ended with %d\n", wait_pid, status);
exit(0);
}
and the problem is that it prints some weird characters at the end.
I really don't know what's wrong with it.
The weir output:
1. from forked child number: 1
2. from forked child number: 1
3. from forked child number: 1
R��process: 6008 ended with 0
I'm writing a program which use fork() and I need to read output from child process in parent process
That I did like this:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <errno.h>
int main(void)
{
int pipefd1[2], pipefd2[2], pipefd3[2];
pid_t pid1, pid2, pid3, wait_pid;
int status;
int i;
int pipefd[2];
if(pipe(pipefd1) == -1){
fprintf(stderr, "Error: %s\n", strerror(errno));
exit (EXIT_FAILURE);
}
char buffer[1024];
switch(pid1 = fork()){
case -1: //fail
fprintf(stderr, "Error: fork 1\n");
exit(1);
case 0: //potomok
close(pipefd1[0]);
dup2(pipefd1[1], 1);
dup2(pipefd1[1], 2);
close(pipefd1[1]);
fprintf(stdout ,"1. from forked child number: 1\n");
fprintf(stdout ,"2. from forked child number: 1\n");
fprintf(stdout ,"3. from forked child number: 1\n");
exit(0);
break;
default:
close(pipefd1[1]); // close the write end of the pipe in the parent
while (read(pipefd1[0], buffer, sizeof(buffer)) > 0){
printf("%s", buffer);
}
}
wait_pid = wait(&status);
printf("process: %d ended with %d\n", wait_pid, status);
exit(0);
}
and the problem is that it prints some weird characters at the end.
I really don't know what's wrong with it.
The weir output:
1. from forked child number: 1
2. from forked child number: 1
3. from forked child number: 1
R��process: 6008 ended with 0