// edtest.cpp #include #include #include #include #include int main(int argc, char** argv) { int p[2]; //printf("[0] making a pipe\n"); pipe(p); char* filename = argv[1]; //printf("[0] forking\n"); pid_t cpid = fork(); if(cpid == -1) { fprintf(stderr,"fork failed\n"); exit(2); } if(cpid == 0) { //printf("[1] closing fds\n"); close(0); close(1); #ifndef WORKING close(2); // if you comment out this line, the program works fine #endif dup2(p[0], 0); //printf("[1] execlp \n"); execlp("ed", "ed", filename, 0); exit(1); // we only reach here in case of an error! } //printf("[0] opening pipe\n"); FILE *cmd = fdopen(p[1], "w"); //printf("[0] sending commands\n"); fprintf(cmd, ",s/hello/goodbye/g\n"); fprintf(cmd, "w\n"); fprintf(cmd, "Q\n"); //printf("[0] flushing commands\n"); fflush(cmd); int status; //printf("[0] checking status \n"); waitpid(0, &status, 0); if(WIFEXITED(status)) { fprintf(stderr, "ed retval=%d\n",WEXITSTATUS(status)); } else { fprintf(stderr, "ed terminated abnormally\n"); } return 0; }