1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <signal.h>
#define FIFO "/tmp/fifo" #define MAX_BUFFER_SIZE PIPE_BUF
pid_t pid, pr; char buff[MAX_BUFFER_SIZE];
void child_func(int sign_no) { if (sign_no == SIGALRM) { int fdChild = open(FIFO, O_WRONLY); if (fdChild == -1) { printf("Open fifo file error\n"); exit(1); } sscanf("this is progress 1\n", "%[^\n]", buff); write(fdChild, buff, MAX_BUFFER_SIZE); close(fdChild); } else if (sign_no == SIGQUIT) { int fdChild = open(FIFO, O_WRONLY); if (fdChild == -1) { printf("Open fifo file error\n"); exit(1); } sscanf("QUIT\n", "%[^\n]", buff); write(fdChild, buff, MAX_BUFFER_SIZE); close(fdChild); printf("process 1 exit.\n"); exit(0); } }
int main() { pid = fork();
if (pid < 0) { printf("Fork error\n"); exit(1); } else if (pid == 0) { signal(SIGALRM, child_func); signal(SIGQUIT, child_func); while (1) { alarm(5); sleep(5); } } else { if (access(FIFO, F_OK) == -1) { if ((mkfifo(FIFO, 0666) < 0) && errno != EEXIST) { printf("Cannot create fifo file\n"); exit(1); } }
int fdParent = open(FIFO, O_RDONLY); if (fdParent == -1) { printf("Open fifo file error\n"); exit(1); } do { signal(SIGQUIT, child_func); pr = waitpid(pid, NULL, WNOHANG); memset(buff, 0, sizeof(buff));
read(fdParent, buff, MAX_BUFFER_SIZE); if (strcmp("", buff) == 0) continue; if (strcmp("QUIT", buff) == 0) exit(0); printf("%s\n", buff); sleep(1); } while (pr == 0); close(fdParent); } exit(0); }
|