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 82
| #include <unistd.h> #include <stdio.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> pid_t id1=0; pid_t id2=0; void shutDown(int sig) { kill(id1,sig); kill(id2,sig); int status; waitpid(id1, &status, WUNTRACED | WCONTINUED); waitpid(id2, &status, WUNTRACED | WCONTINUED); printf("Parent process is killed\n"); _exit(0); } void closed1(int sig) { printf("child process is killed by parent\n"); _exit(0); } void closed2(int sig) { printf("child process2 is killed by parent\n"); _exit(0); } int main() { int fd=open("mypfifo",O_CREAT|O_WRONLY,0666); pid_t id2=fork(); if(id2>0) { pid_t id1=fork(); if(id1>0) { signal(SIGINT,shutDown); while(true) { if(lockf(1,F_LOCK,0)==-1) { printf("加锁失败\n"); } printf("我是主进程\n"); sleep(1); if(lockf(1,F_ULOCK,0)==-1) { printf("解锁失败\n"); } } } else { fd=open("mypfifo",O_WRONLY,0666); signal(SIGINT,closed2); while(true) { lockf(1,F_LOCK,0); printf("我是2号子进程\n"); sleep(1); lockf(1,F_ULOCK,0); } } } else { fd=open("mypfifo",O_WRONLY,0666); signal(SIGINT,closed1); while(true) { lockf(1,F_LOCK,0); printf("我是1号子进程\n"); sleep(1); lockf(1,F_ULOCK,0); } } }
|