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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <syslog.h> #include <sys/types.h> #include <sys/wait.h>
int main() { pid_t child, child1, child2, daemon; int i, fd, sid; char* message1 = "this is a process 2.\n"; char* message2 = "this is a process 3.\n";
child1 = fork();
if (child1 < 0) { printf("Child1 fork error.\n"); exit(1); } else if (child1 == 0) { if (execlp("cp", "cp", "/bin/ls", "/tmp", NULL) < 0) { printf("Child1"); } sleep(2); exit(0); } else {
child2 = fork();
if (child2 == -1) { printf("Child2 fork error.\n"); exit(1); } else if (child2 == 0) { if ((fd = open("./src_file", O_CREAT|O_WRONLY|O_APPEND, 0600)) < 0) { printf("Open file error.\n"); exit(1); } write(fd, message1, strlen(message1) + 1); sleep(5); exit(0); }
do { child = waitpid(child1, NULL, WNOHANG); if (child == 0) { printf("child1 is running.\n"); sleep(1); } } while (child == 0);
do { child = waitpid(child2, NULL, WNOHANG); if (child == 0) { printf("child2 is running.\n"); sleep(1); } } while (child == 0);
daemon = fork();
openlog("test_syslog", LOG_PID, LOG_DAEMON);
if (daemon < 0) { printf("Daemon fork error.\n"); exit(1); } else if (daemon > 0) { exit(0); }
if ((sid = setsid()) < 0) { syslog(LOG_ERR, "%s\n", "setsid"); exit(1); }
if ((sid = chdir("/")) < 0) { syslog(LOG_ERR, "%s\n", "chdir"); exit(1); }
umask(0); for (i = 0; i < getdtablesize(); i++) { close(i); }
while (1) { if ((fd = open("/var/log/message", O_CREAT|O_WRONLY|O_APPEND, 0600)) < 0) { syslog(LOG_ERR, "open"); exit(1); }
write(fd, message2, strlen(message2) + 1); close(fd); sleep(5); }
closelog(); exit(0); }
exit(0); }
|