Hey,
Im a complete noob in UNIX and this problem is killing me.
Im trying to write the stdin (which i receive from a pipe) to a file, but as always C crashes without no explanation. Here is what i have so far:
Code:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void) {
pid_t childpid;
int fd[2];
int file;
mode_t fd_mode=S_IRWXU;
if ((pipe(fd) == -1) || ((childpid = fork()) == -1)) {
perror("Failed to setup pipeline");
return 1;
}
if(childpid>0) {
// send output to the pipe
printf("I am parent\n");
if (dup2(fd[1], STDOUT_FILENO) == -1)
perror("Failed to redirect stdout of ls");
else if ((close(fd[0]) == -1) || (close(fd[1]) == -1))
perror("Failed to close extra pipe descriptors on ls");
else {
execl("input",NULL); // input is an executable which produces
// 2 lines of text
perror("Failed to exec output file");
}
return 1;
}
// receive input from the pipe
printf("I am child\n");
if (dup2(fd[0], STDIN_FILENO) == -1)
perror("Failed to redirect stdin of writing to file");
else if ((close(fd[0]) == -1) || (close(fd[1]) == -1))
perror("Failed to close extra pipe file descriptors");
else {
if((file=open("file1.txt",O_WRONLY | O_CREAT,fd_mode))==-1)
perror("Error opening the file");
char *buffer=(char *)malloc(200);
fgets(buffer,100,STDIN_FILENO); // this should in theory write 100
// characters to the buffer from stdin, but it kills the program
write(file,buffer,100);
perror("Failed to write to the pipe");
}
return 1;
}
Thanx...