1.守护进程创建
定义:周期性的执行某项任务或等待某个事件发生的进程,它的运行不依赖任何shell终端,它的生存周期较长,从开机开始运行直到关机结束。
守护进程的创建步骤:
1.创建一个子进程,让父进程退出 fork
2.在子进程中创建新的会话 setsid();
3.改变子进程的工作目录 chdir(“/”)
4.取消文件权限掩码 umask(0);
5.关闭所有文件描述符 getdtablesize
include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
int i = 0;
//1.fork创建子进程
pid_t pid = -1;
pid = fork();
if(-1 == pid)
{
return -1;
}
if(pid > 0)
{
exit(0);
}
printf("\n1:fork ok!\r\n");
//2.set new section创建新的会话
setsid();
printf("2:create new section ok! pid = %d\r\n", getpid());
//3.chdir
chdir("/");
//4.umask(0)
umask(0);
//5.close all file
int num = getdtablesize();
for(i = 0; i < num; i++)
{
close(i);
}
sleep(20);
return 0;
}
2.线程
定义:线程是一种轻量级的进程,用task_struct来标识它,它没有自己独立内存空间,它共享创建它的进程的地址空间。
2.线程创建
使用第三方线程库提供的API
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
作用:创建一个线程
参数1:*thread:指向线程ID的指针
参数2:*attr:线程属性,通常给NULL
参数3:指向线程执行函数的函数指针
参数4:传给线程执行函数的入参
返回值:0成功,非0失败
#include <stdio.h>
#include <pthread.h>
void *ThreadFunc(void *arg)
{
printf("test by all@1201---------\r\n");
}
int main()
{
printf("hello world\n");
pthread_t tID = -1;
if(0 != pthread_create(&tID, NULL, ThreadFunc, NULL))
{
printf("create pthread error!--------\r\n");
return -1;
}
sleep(1);
printf("hello 22101-----------\r\n")