Skip to content
This repository was archived by the owner on Feb 1, 2022. It is now read-only.

Commit 1228b2b

Browse files
committed
add test_signal.c
Change-Id: Iad9a0eda64ecd7a2bd3519e3f6e54bbe9d127f85
1 parent e9e9ecb commit 1228b2b

File tree

3 files changed

+76
-15
lines changed

3 files changed

+76
-15
lines changed

notes/10/code/Makefile

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
2-
CC = gcc
3-
CFLAGS = -I../.. -Wall
4-
LDFLAGS =
5-
LDLIBS =
6-
7-
PROGS +=
8-
9-
all: ${PROGS}
10-
11-
%: %.c
12-
$(CC) $(CFLAGS) $@.c -o $@ $(LDFLAGS) $(LDLIBS)
13-
14-
clean:
15-
rm -f $(PROGS) *.o
1+
2+
CC = gcc
3+
CFLAGS = -I../.. -Wall
4+
LDFLAGS =
5+
LDLIBS =
6+
7+
PROGS += test_signal
8+
9+
all: ${PROGS}
10+
11+
%: %.c
12+
$(CC) $(CFLAGS) $@.c -o $@ $(LDFLAGS) $(LDLIBS)
13+
14+
clean:
15+
rm -f $(PROGS) *.o

notes/10/code/test_signal.c

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#include <unistd.h>
2+
#include <signal.h>
3+
#include <stdio.h>
4+
#include <errno.h>
5+
#include <string.h>
6+
#include <stdlib.h>
7+
#include <sys/wait.h>
8+
9+
void sig_chld(int signo)
10+
{
11+
int status;
12+
pid_t pid;
13+
printf("signo = %d\n", signo);
14+
15+
while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
16+
{
17+
printf("%d exits, status = %d\n", pid, status);
18+
}
19+
}
20+
21+
int main()
22+
{
23+
pid_t pid = 0;
24+
void (*old_sig_chld)(int) = signal(SIGCHLD, sig_chld);
25+
if (old_sig_chld == SIG_ERR)
26+
{
27+
printf("signal error, errno = %d, %s\n", errno, strerror(errno));
28+
exit(errno);
29+
}
30+
else if (old_sig_chld == SIG_IGN)
31+
{
32+
printf("old SIGCHLD handler = SIG_IGN\n");
33+
}
34+
else if (old_sig_chld == SIG_DFL)
35+
{
36+
printf("old SIGCHLD handler = SIG_DFL\n");
37+
}
38+
else
39+
{
40+
printf("old SIGCHLD handler = %p\n", old_sig_chld);
41+
}
42+
43+
pid = fork();
44+
if (pid < 0)
45+
{
46+
printf("fork error, errno = %d, %s", errno, strerror(errno));
47+
exit(errno);
48+
}
49+
50+
if (pid == 0)
51+
{
52+
// child
53+
exit(0);
54+
}
55+
56+
sleep(2);
57+
58+
return 0;
59+
}

notes/10/notes.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,8 @@ exec调用:
131131
fork调用:
132132
* 子进程继承父进程的信号处理方式。因为信号捕捉函数的地址在子进程中是有意义的。
133133
134+
示例代码:<a href="code/test_signal.c">test_signal.c</a>
135+
134136
---
135137
136138
[章节目录](../../README.md#title_ch10 "返回章节目录")

0 commit comments

Comments
 (0)