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

文件名称process.c

/**

* Manage the process and thread

* @author:zhoubaochuan

* @date:2011-07-13

*/

#include

#include

#include

#include

#include

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值