c - using sort with dup2 -
i'm experimenting dup2 command in linux. i've written code follows:
#include <stdio.h> #include <unistd.h> #include <string.h> int main() { int pipe1_ends[2]; int pipe2_ends[2]; char string[] = "this \n \n not \n sorted"; char buffer[100]; pid_t pid; pipe(pipe1_ends); pipe(pipe2_ends); pid = fork(); if(pid > 0) { /* parent */ close(pipe1_ends[0]); close(pipe2_ends[1]); write(pipe1_ends[1],string,strlen(string)); read(pipe2_ends[0], buffer, 100); printf("%s",buffer); return 0; } if(pid == 0) { /* child */ close(pipe1_ends[1]); close(pipe2_ends[0]); dup2(pipe1_ends[0], 0); dup2(pipe2_ends[1],1); char *args[2]; args[0] = "/usr/bin/sort"; args[1] = null; execv("/usr/bin/sort",args); } return 0; }
i expect program behave follows: should fork child , replace image sort process. , since stdin , stdout replaced dup2 command, expect sort read input pipe , write output other pipe printed parent. sort program doesn't seem reading input. if no commandline argument given, sort reads stdin right? can me problem, please.
many thanks!
hm. what's happening aren't finishing write: after sending data child process, have tell you're done writing, either closing pipe1_ends[1] or calling shutdown(2)
on it. should call write/read in loop, since it's quite in general case read @ least won't give results in 1 go. full code checks return values, doesn't it?
one final thing: printf badly broken. can accept null-terminated strings, , result returned read
not null-terminated (it's buffer-with-length, other common way of knowing end is). want:
int n = read(pipe2_ends[0], buffer, 99); if (n < 0) { perror("read"); exit(1); } buffer[n] = 0; printf("%s",buffer);
Comments
Post a Comment