六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 34|回复: 0

第二章 C语言实例 — 进程和线程管理

[复制链接]

升级  9%

63

主题

63

主题

63

主题

举人

Rank: 3Rank: 3

积分
227
 楼主| 发表于 2013-1-26 12:37:20 | 显示全部楼层 |阅读模式
文件名称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  
要看到实际效果就把守护进程的那块代码去掉。
 
 
 
守护进程:脱离于终端并且在后台运行的进程。脱离于终端是为了避免进程在执行过程中的信息在任何终端上显示并且进程也不会被任何终端所产生的终端信息所打断。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表