APUE course source code
guowenxue
2 days ago 68826376ee5f47783c644c6604f4411ec747cd7e
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
/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  signal.c
 *    Description:  This file is signal example program
 *
 *        Version:  1.0.0(11/07/2025)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "11/07/2025 10:18:12 AM"
 *
 ********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
 
int g_child_stop = 0;
int g_parent_run = 0;
 
void sig_child(int signum)
{
    if( SIGUSR1 == signum )
    {
        g_child_stop = 1;
    }
}
 
void sig_parent(int signum)
{
    if( SIGUSR2 == signum )
    {
        g_parent_run = 1;
    }
}
 
int main(int argc, char **argv)
{
    int             pid;
    int             wstatus;
 
    signal(SIGUSR1, sig_child);
    signal(SIGUSR2, sig_parent);
 
    if( (pid=fork()) < 0 )
    {
        printf("Create child process failure: %s\n", strerror(errno));
        return -2;
    }
    else if(pid == 0)
    {
        /* child process can do something first here */
        printf("Child process working...\n");
        sleep(1);
 
        printf("Child process done and send parent signal SIGUSR2\n");
        kill(getppid(), SIGUSR2);
 
        while( !g_child_stop )
        {
            sleep(1);
        }
 
        printf("Child process receive signal from parent and exit now\n");
        return 0;
    }
 
    printf("Parent hangs up to wait for signal from child\n");
    while( !g_parent_run )
    {
        sleep(1);
    }
 
    /* parent process can do something here */
    printf("Parent process working...\n");
    sleep(1);
 
    printf("Parent process done and send child signal SIGUSR1\n");
    kill(pid, SIGUSR1);
 
    /* parent wait child process exit */
    wait(&wstatus);
    printf("Parent process receive signal from child and exit now\n");
 
    return 0;
}