Linux多线程 作业

要求

父进程创建 3 个进程,父进程等待子进程 2 运行完成之后,自行退出;其中子进程 1 运行系统命令“cp /bin/ls /tmp”;等待 2 秒后退出;子进程 2 使用标准 I/O 函数打开文件 src_file,向其内写入“this is process 2\n”,之后等待 5 秒后退出;子进程 3 处理为守护进程,每隔 5 秒向日志文件/var/log/messages 写入“this is process 3\n”

提交形式

  1. 代码
  2. 运行结果截图

Code

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) { // child1 thread
if (execlp("cp", "cp", "/bin/ls", "/tmp", NULL) < 0) {
printf("Child1");
}
sleep(2);
exit(0);
} else { // father thread

child2 = fork();

if (child2 == -1) {
printf("Child2 fork error.\n");
exit(1);
} else if (child2 == 0) { // child2 thread
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(); // fork daemon

openlog("test_syslog", LOG_PID, LOG_DAEMON); // open syslog

if (daemon < 0) {
printf("Daemon fork error.\n");
exit(1);
} else if (daemon > 0) {
exit(0); // father thread exit
}

if ((sid = setsid()) < 0) {
syslog(LOG_ERR, "%s\n", "setsid");
exit(1);
}

if ((sid = chdir("/")) < 0) {
syslog(LOG_ERR, "%s\n", "chdir");
exit(1);
}

// start make daemon thread
umask(0);
for (i = 0; i < getdtablesize(); i++) {
close(i);
}

while (1) { // start run daemon thread
if ((fd = open("/var/log/message", O_CREAT|O_WRONLY|O_APPEND, 0600)) < 0) { // get the fildes
syslog(LOG_ERR, "open");
exit(1);
}

write(fd, message2, strlen(message2) + 1);
close(fd);
sleep(5);
}

closelog();
exit(0);
}

exit(0);
}