pe52.c

#include <stdio.h>​ #include <unistd.h>​ #include <stdlib.h>​ #include <string.h>​ #include <sys/types.h>​ #include <sys/wait.h>​ ​ int​ main(int argc, char * argv[]) {​ int f_des[2], i=0, j=0, intValue[argc-1], sum=0, status;​ static char value[BUFSIZ], sumStr[10];​ if (argc < 2) {​ fprintf(stderr, "Usage: %s followed by at least ​ one integer\n", *argv);​ exit(1);​ } ​ if (pipe(f_des) == -1) {​ printf("Pipe creation failed.\n");​ exit(2);​ }​ if (fork() == 0) {​ for (i=1; i<argc; i++) { ​ read(f_des[0], value, strlen(argv[i]));​ intValue[i-1] = atoi(value);​ sum+=intValue[i-1];​ }​ sprintf(sumStr, "%d", sum);​ write(f_des[1], sumStr, strlen(sumStr));​ exit(3);​ } else {​ j=1;​ while (argv[j] != NULL) {​ write(f_des[1], argv[j], strlen(argv[j]));​ j++;​ }​ wait(&status);​ read(f_des[0], value, BUFSIZ);​ printf("Sum=%s\n", value);​ }​ }​

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.