1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- #include "cmd_test.h"
- #include <math.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <time.h>
- #include <unistd.h>
- #define buf_SIZE 256
- int shell_pipe_test(int argc, char **argv)
- {
- int fd[2], i, n;
- pid_t pid;
- int ret = pipe(fd);
- if (ret < 0)
- {
- printf("pipe error");
- exit(1);
- }
- pid = fork();
- if (pid < 0)
- {
- printf("fork error");
- exit(1);
- }
- if (pid == 0)
- {
- close(fd[1]);
- for (i = 0; i < 3; i++)
- {
- char buf[buf_SIZE] = {0};
- n = read(fd[0], buf, buf_SIZE);
- if (n > 0)
- {
- printf("Child process received message: %s\n", buf);
- if (strcmp(buf, "quit") == 0)
- {
- printf("Child process exits.\n");
- break;
- }
- else
- {
- printf("Child process is doing something...\n");
- usleep(100);
- }
- }
- }
- close(fd[0]);
- exit(0);
- }
- else
- {
- close(fd[0]);
- for (i = 0; i < 3; i++)
- {
- char *msg = "hello world";
- if (i == 1)
- {
- msg = "how are you";
- usleep(1000);
- }
- if (i == 2)
- {
- msg = "quit";
- usleep(1000);
- }
- n = strlen(msg);
- printf("Parent process send:%s\n", msg);
- write(fd[1], msg, n);
- if (strcmp(msg, "quit") == 0)
- {
- printf("Parent process exits.\n");
- break;
- }
- }
- close(fd[1]);
- wait(NULL);
- }
- return 0;
- }
|