Hi jeanluca, I think you just got it the wrong way round :) You have to dup the output side of the pipe to file descriptor 63 (my_prog.pl needs to write to the output side...), and then simply read from the input side within your C program. Also, it's more common to swap the roles of parent and child, i.e. run the command in the child (via one of the exec functions), and read its output in the parent process. Here's a modified version of your program that should work (with my_prog.pl as you had it):
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/wait.h> int main() { const char *cmd = "./my_prog.pl"; const int RESPONSE_FD = 63; int pfd[2], status; char buffer[100]; int rv; status = pipe(pfd); if(status == -1) { printf("Could not open pipe\n"); exit(1); } else { printf("The filedescriptors are: %d %d\n", pfd[0], pfd[1]); } status = fork(); if(status == 0) { printf("This is the child\n"); /* dup output/writing side of pipe */ status = dup2(pfd[1], RESPONSE_FD); /* close unused input side */ close(pfd[0]); if(status == -1) { printf("dup2 failed\n"); exit(1); } execl(cmd, cmd, (char *)0); } else { printf("This is the parent\n"); /* close unused output side of pipe */ close(pfd[1]); /* read from input side */ while(read(pfd[0], buffer, sizeof(buffer))>0) { printf("%s", buffer); } wait(&rv); fprintf(stderr,"%s exited with value %d\n", cmd, rv); } return 0; }
Output:
The filedescriptors are: 4 6 This is the child This is the parent this is a message ./my_prog.pl exited with value 0
Update: minor fixes, so that it also does compile with -Wall :)
In reply to Re: communication between C and perl
by almut
in thread communication between C and perl
by jeanluca
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |