From ff94a13ba95f9ce6697ef47c95071dd9b2ab424e Mon Sep 17 00:00:00 2001 From: Guo Wenxue <guowenxue@gmail.com> Date: Wed, 05 Dec 2018 21:23:23 +0800 Subject: [PATCH] Add IPC singal.c sample code --- ch6_ipc/signal.c | 76 ++++++++++++++++++++++++++++++++++++++ 1 files changed, 76 insertions(+), 0 deletions(-) diff --git a/ch6_ipc/signal.c b/ch6_ipc/signal.c new file mode 100644 index 0000000..17230e5 --- /dev/null +++ b/ch6_ipc/signal.c @@ -0,0 +1,76 @@ +#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, then tell parent process to start running */ + + printf("Child process start running and send parent a signal\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 untill receive signal from child!\n"); + while( !g_parent_run ) + { + sleep(1); + } + + /* parent process can do something here, then tell child process to exit */ + + printf("Parent start running now and send child a signal to exit\n"); + kill(pid, SIGUSR1); + + /* parent wait child process exit */ + wait(&wstatus); + printf("Parent wait child process die and exit now\n"); + + return 0; +} + + -- Gitblit v1.9.1