// Ivan Novick // Feb 3, 2008 // pipe_write_read.c // basic opening of a pipe, forking a child process, then the child writes to parent over the pipe #include #include #include #include #include int pipe_fd[2]; pid_t me; pid_t parent; char buffer[512]; int main(int argc, char** argv) { // create a pipe if (pipe(pipe_fd)) { fprintf(stderr, "pipe creation failed, exiting...\n"); exit(1); } int fork_return = fork(); if (fork_return < 0) { fprintf(stderr, "fork failed, exiting...\n"); exit(2); } // obtain the pid of this process and the parent pid_t me = getpid(); pid_t par = getppid(); printf("PID: %d, PARENT: %d\n", (int)me, (int)par); // determine if this is the parent or child process if (fork_return == 0) { // if fork returned 0, this is the child sprintf(buffer, "Hi parent, my pid is %d", me); // actually write to the pipe now size_t amount = write(pipe_fd[1], buffer, strlen(buffer) + 1); printf("wrote to pipe %d bytes\n", (int)amount); } else { // fork returned > 0 this is the parent process // actually read from the pipe now ssize_t amount = read(pipe_fd[0], buffer, sizeof(buffer)); printf("read from pipe %d bytes\n", (int)amount); printf("in parent, message from child over pipe: %s\n", buffer); } return 0; }