// // PARENT PROCESS // (child below) #include #include #include #include int main (int argc, const char * argv[]) { int pipefd[2]; pid_t pid; int writeEnd, readEnd; int i; char *path = "/path/to/ForkChild"; char *arg0 = "ForkChild"; char arg1[10]; int rc; char buffer[256]; int bufferSize = 256; // let's create some pipes for the instance if(pipe(pipefd) < 0) { perror("pipe failed"); return -1; } writeEnd = pipefd[1]; readEnd = pipefd[0]; pid = fork(); switch(pid) { case -1: perror("fork"); return -1; case 0: // ******** child ********** sprintf(arg1, "%d", writeEnd); if(execl(path, arg0, arg1, NULL) == -1) { perror("error spawning child"); } break; default: // ******* parent ********** // clear the buffer for(i = 0; i < bufferSize; i++) buffer[i] = 0; // Listen for messages coming on read end of pipe rc = read(readEnd, buffer, bufferSize); printf("buffer=%s\n", buffer); break; } return 0; } // ForkChild code #include int main(int argc, const char * argv[]) { int fd; if(argc >= 2) { // translate first argument fd = atoi(argv[1]); FILE *outFP = fdopen(fd, "w"); fprintf(outFP, "Test\n"); fclose(outFP); } return 0; }