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

pbyanglove 2011-07-14

文件名称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
 

要看到实际效果就把守护进程的那块代码去掉。

守护进程:脱离于终端并且在后台运行的进程。脱离于终端是为了避免进程在执行过程中的信息在任何终端上显示并且进程也不会被任何终端所产生的终端信息所打断。

相关推荐