#include #include #include #include #include #define MAX 256 /** * This program shows what can happen when multiple processes * try to indiscrimately share a file descriptor, in this * stdin. * For best results, pipe the output of some "difficult" UNIX * command into this sample, like 'du', which calculates hard * disk usage between printing out lines. * * du -s /usr/lib/* | ./sharedIn * * What determines which process gets an input line? * Run the command again; what are some of the factors that cause * different results across runs? * What is the important lesson to learn here about sharing open * file descriptors (like stdin and stdout)? */ int main() { pid_t pid; char s[MAX + 1]; int i = 0; for (i = 0; i < MAX + 1; i++) s[i] = '\0'; i = 0; pid = fork(); /* fork another process */ if (pid < 0) /* Forking error! */ { exit(-1); } else if (0 == pid) /* Child process */ { // Read in characters until string is full or EOF. while ((i < MAX) && ( (s[i++] = getchar()) != EOF) && !feof(stdin)) ; // Print out what we got. printf("Child got \"%s\"\n", s); exit(0); } else /* pid > 0: Parent process */ { // Read in characters until string is full or EOF. while ((i < MAX) && ( (s[i++] = getchar()) != EOF) && !feof(stdin)) ; // Print out what we got. printf("Parent got \"%s\"\n", s); // Wait for the child; this is good etiquette, and ensures that // the O/S cleans up certain resources. wait(NULL); // What happens if the parent process exits without waiting for // the child process to finish? exit(0); } }