父子进程通信
Posted on 2012年9月12日 15:04父
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> int main() { int data_processed; int file_pipes[2]; const char some_data[] = "123"; char buffer[BUFSIZ + 1]; pid_t fork_result; memset(buffer, '\0', sizeof(buffer)); if (pipe(file_pipes) == 0) { fork_result = fork(); if (fork_result == -1) { fprintf(stderr, "Fork failure"); exit(EXIT_FAILURE); } /* child */ if (fork_result == 0) { sprintf(buffer, "%d", file_pipes[0]); (void)execl("pipe4", "pip4", buffer, (char *)0); exit(EXIT_FAILURE); } else { /* parent */ data_processed = write(file_pipes[1], some_data, strlen(some_data)); printf("%d - Wrote %d bytes\n", getpid(),data_processed); } } exit(EXIT_SUCCESS); }
子
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { int data_processed; char buffer[BUFSIZ + 1]; int file_descriptor; memset(buffer, '\0', sizeof(buffer)); sscanf(argv[1], "%d", &file_descriptor); data_processed = read(file_descriptor, buffer, BUFSIZ); printf("%d - read %d bytes: %s\n", getpid(), data_processed, buffer); exit(EXIT_SUCCESS); }
30510 - Wrote 3 bytes
30511 - read 3 bytes: 123