第二章 C语言实例 — 进程和线程管理
文件名称process.c
/** * Manage the process and thread * @author:zhoubaochuan * @date:2011-07-13 */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <signal.h> #include <pthread.h> static void handle_thread(const int sig); static void handle_signal(const int sig); int main(int argc,char *argv[]){ /*FILE *fp; fp = fopen(destination,"w"); fprintf(fp,"pid:\n",getpid()); fclose(fp);*/ /* 守护进程 {{{*/ pid_t pid; pid = fork(); if(pid < 0){ /* Create process is failure */ exit(1); } if(pid > 0){ /* Stop the current process(parent process) */ exit(1); } /* 守护进程 end}}} */ pid_t pid1 = fork(); if(pid1 < 0){ fprintf(stderr, "Error: %s:%d\n", __FILE__, __LINE__); exit(1); } /* Parent process'id is > 0,and child process'id is == 0 */ if(pid1 > 0){ /* Handle process*/ signal(SIGPIPE, SIG_IGN); signal (SIGINT, handle_signal); signal (SIGKILL, handle_signal); signal (SIGQUIT, handle_signal); signal (SIGTERM, handle_signal); signal (SIGHUP, handle_signal); signal(SIGSEGV, handle_signal); /* If the child process stop, create new child process */ pid_t pid2; while(1){ pid2 = wait(NULL); if(pid2 < 0){ /*The child process error */ continue; } /* The child process have stoped */ usleep(100000); pid1 = fork(); if(pid1 == 0){ /* In Child process,end the loop! */ break; } } } /* Child Process */ printf("The child process is carrying out! \n"); signal(SIGPIPE, SIG_IGN); signal (SIGINT, handle_signal); signal (SIGKILL, handle_signal); signal (SIGQUIT, handle_signal); signal (SIGTERM, handle_signal); signal (SIGHUP, handle_signal); signal(SIGSEGV, handle_signal); /* The child process handle */ pthread_t tid; pthread_create(&tid, NULL, (void *)handle_thread, NULL); return 0; } static void handle_signal(const int sig){ kill(0, SIGTERM); exit(0); } static void handle_thread(const int sig){ printf("The thread is processing ! \n"); pthread_detach(pthread_self()); }
由于要用到线程库所以在编译时使用如下方式.
gcc process.c -lpthread
要看到实际效果就把守护进程的那块代码去掉。
守护进程:脱离于终端并且在后台运行的进程。脱离于终端是为了避免进程在执行过程中的信息在任何终端上显示并且进程也不会被任何终端所产生的终端信息所打断。
相关推荐
chensen 2020-11-14
拉斯厄尔高福 2020-11-04
杜倩 2020-10-29
拉斯厄尔高福 2020-10-19
嵌入式资讯精选 2020-10-15
zhaochen00 2020-10-13
penkgao 2020-10-13
yiyilanmei 2020-10-05
wanshiyingg 2020-09-29
Mars的自语 2020-09-27
shenwenjie 2020-09-24
一个逗逗 2020-09-22
flycony 2020-09-13
zhaochen00 2020-08-20
Biao 2020-08-20
qingsongzdq 2020-08-19
penkgao 2020-08-17
cetrolchen 2020-08-14
GuoSir 2020-08-07