6、守护进程、线程(linux系统编程)

1 守护进程介绍

Daemon(精灵)进程,是Linux中的后台服务进程,
通常独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。

守护进程的特点:

1 一个linux后台服务进程
2 不依赖于控制终端
3 周期性执行某些任务
4 不受用户登录和注销的影响
5 一般以d结尾

进程组和会话:

进程组: 一个进程包含多个进程
会话: 多个组组成一个会话.

创建会话的进程不能是组长进程;
一般创建会话是父进程先fork子进程, 然后父进程退出, 让子进程调用setsid函数
创建一个会话, 这个子进程既是会长也是组长;
只要是创建了会话, 这个进程就脱离了控制终端的影响.

创建守护进程模型:

1 父进程fork子进程, 然后父进程退出.
   目的是: 子进程肯定不是组长进程, 为后续调用setsid函数提供了条件.
2 子进程调用setsid函数创建一个新的会话.
	1 该子进程成了该会话的会长
	2 该子进程成了该组的组长进程.
	3 不再受控制终端的影响了
3 改变当前的工作目录, chdir  -----不是必须的
4 重设文件掩码, umask(0000)  -----不是必须的
5 关闭STDIN_FILENO  STDOUT_FILENO STDERR_FILENO   ---不是必须的
6 核心操作

编写一个守护进程,每隔2S钟获取一次系统时间,并将这个时间写入磁盘文件。

分析:首先要按照1.3介绍的守护进行的步骤创建一个守护进程.
每隔2S钟: 使用setitimer函数设置时钟, 该时钟发送的是SIGALRM信号,
信号操作: 注册信号处理函数,signal或者sigaction, 还有一个信号处理函数
获取一次系统时间: time函数的使用, ctime函数的使用
写入磁盘文件: 文件操作函数: open write close

//mydeamon.c
//创建守护进程
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>

void myfunc(int signo)
{
	//打开文件
	int fd = open("mydemon.log", O_RDWR | O_CREAT | O_APPEND, 0755);
	if(fd<0)
	{
		return;
	}

	//获取当前的系统时间
	time_t t;
	time(&t);
	char *p = ctime(&t);
	
	//将时间写入文件
	write(fd, p, strlen(p));

	close(fd);

	return;
}

int main()
{
	//父进程fork子进程, 然后父进程退出
	pid_t pid = fork();
	if(pid<0 || pid>0)
	{
		exit(1);
	}
	
	//子进程调用setsid函数创建会话
	setsid();

	//改变当前的工作目录
	chdir("/home/itcast/log");

	//改变文件掩码
	umask(0000);

	//关闭标准输入,输出和错误输出文件描述符
	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);

	//核心操作
	//注册信号处理函数
	struct sigaction act;
	act.sa_handler = myfunc;
	act.sa_flags = 0;
	sigemptyset(&act.sa_mask);	
	sigaction(SIGALRM, &act, NULL);

	//设置时钟
	struct itimerval tm;
	tm.it_interval.tv_sec = 2;
	tm.it_interval.tv_usec = 0;
	tm.it_value.tv_sec = 3;
	tm.it_value.tv_usec = 0;
	setitimer(ITIMER_REAL, &tm, NULL);

	printf("hello world\n");

	while(1)
	{
		sleep(1);
	}
}

优化:

1 不再频繁的打开和关闭文件
2 如何控制log文件大小  test.log

//编写守护进程: 每隔2秒获取一次系统时间,并将时间写入文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>

int fd;
int flag = 0;

//信号处理函数
void sighandler(int signo)
{
	//获取当前系统时间
	time_t tm;
	time(&tm);
	char *p = ctime(&tm);

	if(flag==0)
	{
		//新建文件
		fd = open("./mydaemon.log", O_RDWR | O_CREAT | O_APPEND, 0777);
		if(fd<0)
		{
			perror("open error");
			return;
		}
		flag = 1;
	}

	//写文件
	write(fd, p, strlen(p));

	return;
}
int main()
{
	//fork子进程,父进程退出
	pid_t pid = fork();
	if(pid<0 || pid>0)
	{
		exit(0);
	}

	//子进程调用setsid函数创建新会话
	setsid();

	//改变当前工作目录chdir
	chdir("/home/itcast");

	//重设文件掩码
	umask(0000);

	//关闭标准输入,标准输出, 标准错误输出这三个文件描述符
	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);

	//核心工作
	struct sigaction act;
	act.sa_handler = sighandler;
	act.sa_flags = 0;
	sigemptyset(&act.sa_mask);
	sigaction(SIGALRM, &act, NULL);

	//调用setitimer函数设置时钟
	struct itimerval tm;
	tm.it_interval.tv_sec = 2;
	tm.it_interval.tv_usec = 0;
	tm.it_value.tv_sec = 3;
	tm.it_value.tv_usec = 0;
	setitimer(ITIMER_REAL, &tm, NULL);

	while(1)
	{
		//获取文件大小
		int size = lseek(fd, 0, SEEK_END);
		if(size>100)
		{
			close(fd);
			rename("./mydaemon.log", "./mydaemon.log.bak");//文件重命名
			flag =0;
		}
	}

	close(fd);
	
	return 0;
}

线程相关函数:

1 创建子线程: pthread_create
2 线程退出: pthread_exit
3 回收子线程: pthread_join
4 设置子线程为分离属性: pthread_detach

在这里插入图片描述

//创建子线程

	//pthread_create.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>

//线程执行函数
void *mythread(void *arg)
{
	printf("child thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());
}

int main()
{
	//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    //                      void *(*start_routine) (void *), void *arg);
	//创建子线程
	pthread_t thread;
	int ret = pthread_create(&thread, NULL, mythread, NULL);
	if(ret!=0)
	{
		printf("pthread_create error, [%s]\n", strerror(ret));
		return -1;
	}
	printf("main thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());

	//目的是为了让子线程能够执行起来
	sleep(1);
	return 0;
}

//创建子线程: 传递参数

//pthread_create1.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>

struct Test
{
	int data;
	char name[64];
};

//线程执行函数
void *mythread(void *arg)
{
	//int n = *(int *)arg;
	struct Test *p = (struct Test *)arg;
	//struct Test *p = arg;
	//printf("n==[%d]\n", n);
	printf("[%d][%s]\n", p->data, p->name);
	printf("child thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());
}

int main()
{
	int n = 99;
	struct Test t;
	memset(&t, 0x00, sizeof(struct Test));
	t.data = 88;
	strcpy(t.name, "xiaowen");	
	//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    //                      void *(*start_routine) (void *), void *arg);
	//创建子线程
	pthread_t thread;
	//int ret = pthread_create(&thread, NULL, mythread, &n);
	int ret = pthread_create(&thread, NULL, mythread, &t);
	if(ret!=0)
	{
		printf("pthread_create error, [%s]\n", strerror(ret));
		return -1;
	}
	printf("main thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());

	//目的是为了让子线程能够执行起来
	sleep(1);
	return 0;
}

编写程序,主线程循环创建5个子线程,并让子线程判断自己是第几个子线程。

练习4分析:最后每个子线程打印出来的值并不是想象中的值,比如都是5,
分析其原因:
在创建子线程的时候使用循环因子作为参数传递给子线程,
这样主线程和多个子线程就会共享变量i(变量i在main函数中定义,
在整个进程都一直有效)
所以在子线程看来变量i是合法的栈内存空间。
那么为什么最后每个子线程打印出来的值都是5呢?
是由于主线程可能会在一个cpu时间片内连续创建了5个子线程,
此时变量i的值变成了5,
当主线程失去cpu的时间片后,子线程得到cpu的时间片,
子线程访问的是变量i的内存空间的值,所以打印出来值为5.

解决办法:不能使多个子线程都共享同一块内存空间,
	应该使每个子线程访问不同的内存空间,可以在主线程定义一个数组:int arr[5];
	然后创建线程的时候分别传递不同的数组元素,
	这样每个子线程访问的就是互不相同的内存空间,这样就可以打印正确的值。

在这里插入图片描述

//循环创建子线程,并且打印是第几个子线程

	//pthread_create_loop.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>

//线程执行函数
void *mythread(void *arg)
{
	int i = *(int *)arg;
	printf("[%d]:child thread, pid==[%d], id==[%ld]\n", i, getpid(), pthread_self());
	sleep(100);//非必要,为了不让一瞬间退出
}

int main()
{
	//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
	//                      void *(*start_routine) (void *), void *arg);
	//创建子线程
	int ret;
	int i = 0;
	int n = 5;
	int arr[5];
	pthread_t thread[5];
	for(i=0; i<n; i++)
	{
		arr[i] = i;
		ret = pthread_create(&thread[i], NULL, mythread, &arr[i]);
		if(ret!=0)
		{
			printf("pthread_create error, [%s]\n", strerror(ret));
			return -1;
		}
	}
	printf("main thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());

	//目的是为了让子线程能够执行起来
	sleep(100);
	return 0;
}

//线程退出函数测试

//pthread_exit.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>

struct Test
{
	int data;
	char name[64];
};
int g_var = 9;
struct Test t;

//线程执行函数
void *mythread(void *arg)
{
	printf("child thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());
	//printf("[%p]\n", &g_var);
	//pthread_exit(&g_var);
	memset(&t, 0x00, sizeof(t));
	t.data = 99;
	strcpy(t.name, "xiaowen");
	pthread_exit(&t);
}

int main()
{
	//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    //                      void *(*start_routine) (void *), void *arg);
	//创建子线程
	pthread_t thread;
	int ret = pthread_create(&thread, NULL, mythread, NULL);
	if(ret!=0)
	{
		printf("pthread_create error, [%s]\n", strerror(ret));
		return -1;
	}
	printf("main thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());

	//回收子线程
	void *p = NULL;
	pthread_join(thread, &p);	
	//int n = *(int *)p;
	struct Test *pt = (struct Test *)p;
	printf("child exit status:[%d],[%s],[%p]\n",  pt->data, pt->name, p);

	return 0;
}

//设置子线程为分离属性

//pthread_detach.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>

//线程执行函数
void *mythread(void *arg)
{
	printf("child thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());
	sleep(10);
}

int main()
{
	//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    //                      void *(*start_routine) (void *), void *arg);
	//创建子线程
	pthread_t thread;
	int ret = pthread_create(&thread, NULL, mythread, NULL);
	if(ret!=0)
	{
		printf("pthread_create error, [%s]\n", strerror(ret));
		return -1;
	}
	printf("main thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());

	//设置线程为分离属性
	pthread_detach(thread);

	//子线程设置分离属性,则pthread_join不再阻塞,立刻返回
	ret = pthread_join(thread, NULL);
	if(ret!=0)
	{
		printf("pthread_join error:[%s]\n", strerror(ret));
	}

	//目的是为了让子线程能够执行起来
	sleep(1);
	return 0;
}

pthread_cancel函数

函数描述:
杀死(取消)线程。其作用,对应进程中 kill() 函数。
还以通过调用pthread_testcancel函数设置一个取消点。
函数原型:void pthread_testcancel(void);

//pthread_cancel.c
//创建子线程
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>

//线程执行函数
void *mythread(void *arg)
{
	while(1)
	{
		int a;
		int b;

		//设置取消点
		pthread_testcancel();

		printf("-----\n");
		
	}
}

int main()
{
	//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    //                      void *(*start_routine) (void *), void *arg);
	//创建子线程
	pthread_t thread;
	int ret = pthread_create(&thread, NULL, mythread, NULL);
	if(ret!=0)
	{
		printf("pthread_create error, [%s]\n", strerror(ret));
		return -1;
	}
	printf("main thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());

	//取消子线程
	pthread_cancel(thread);

	pthread_join(thread, NULL);
	return 0;
}

pthread_equal函数

函数描述:
比较两个线程ID是否相等。
//pthread_equal.c
//比较线程ID是否相等

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>

//线程执行函数
void *mythread(void *arg)
{
	printf("child thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());
}

int main()
{
	//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    //                      void *(*start_routine) (void *), void *arg);
	//创建子线程
	pthread_t thread;
	int ret = pthread_create(&thread, NULL, mythread, NULL);
	if(ret!=0)
	{
		printf("pthread_create error, [%s]\n", strerror(ret));
		return -1;
	}
	printf("main thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());

	//比较线程ID
	//if(pthread_equal(thread, pthread_self())!=0)
	if(pthread_equal(pthread_self(), pthread_self())!=0)
	{
		printf("two thread id is same\n");
	}
	else
	{
		printf("two thread id is not same\n");
	}

	//目的是为了让子线程能够执行起来
	sleep(1);
	return 0;
}

在创建线程的时候设置线程属性为分离属性:

1 pthread_attr_t attr;
2 pthread_attr_init(&attr);
3 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
4 pthread_create(&thread, &attr, mythread, NULL);
5 pthread_attr_destroy(&attr);

//pthread_attr.c
//在创建子线程的时候设置分离属性
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>

//线程执行函数
void *mythread(void *arg)
{
	printf("child thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());
	sleep(2);
}

int main()
{
	//定义pthread_attr_t类型的变量
	pthread_attr_t attr;
	
	//初始化attr变量
	pthread_attr_init(&attr);

	//设置attr为分离属性
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

	//创建子线程
	pthread_t thread;
	int ret = pthread_create(&thread, &attr, mythread, NULL);
	if(ret!=0)
	{
		printf("pthread_create error, [%s]\n", strerror(ret));
		return -1;
	}
	printf("main thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());

	//释放线程属性
	pthread_attr_destroy(&attr);

	//验证子线程是否为分离属性
	ret = pthread_join(thread, NULL);
	if(ret!=0)
	{
		printf("pthread_join error:[%s]\n", strerror(ret));
	}

	return 0;
}

两个线程数数(利用互斥锁)

//创建子线程 pthread_lock.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>

#define NUM 5000
int number = 0;
//定义一把互斥锁
pthread_mutex_t mutex;

//线程执行函数
void *mythread1(void *arg)
{
		int i =0;
		for(i=0;i<NUM;i++)
		{	
			pthread_mutex_lock(&mutex);
			n = number;
			n++;
			number = n;
			printf("1 number == [%d]\n",number);
			pthread_mutex_unlock(&mutex);
		}	
	
	//printf("child thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());
}

void *mythread2(void *arg)
{
		int i =0;
		for(i=0;i<NUM;i++)
		{	
			pthread_mutex_lock(&mutex);
			n = number;
			n++;
			number = n;
			printf("2 number == [%d]\n",number);
			pthread_mutex_unlock(&mutex);
		}	
	
	//printf("child thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());
}

int main()
{
	//互斥锁初始化
	pthread_mutex_init(&mutex,NULL);
	//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    //                      void *(*start_routine) (void *), void *arg);
	//创建子线程
	pthread_t thread1;
	int ret = pthread_create(&thread1, NULL, mythread1, NULL);
	if(ret!=0)
	{
		printf("pthread1_create error, [%s]\n", strerror(ret));
		return -1;
	}
		
	pthread_t thread2;
	 ret = pthread_create(&thread2, NULL, mythread2, NULL);
	if(ret!=0)
	{
		printf("pthread2_create error, [%s]\n", strerror(ret));
		return -1;
	}
	pthread_join(thread1,NULL);
	pthread_join(thread2,NULL);
	printf("number == [%d]\n",number);
	//printf("main thread, pid==[%d], id==[%ld]\n", getpid(), pthread_self());
	//销毁一个互斥锁
	pthread_mutex_destroy(&mutex);
	//目的是为了让子线程能够执行起来
	sleep(1);
	return 0;
}

线程同步:
互斥锁: 线程A和线程B共同访问共享资源, 当线程A想访问共享资源的时候,
要先获得锁, 如果锁被占用, 则加锁不成功需要阻塞等待对方释放锁;
若锁没有被占用, 则获得锁成功–加锁, 然后操作共享资源, 操作完之后,
必须解锁, 同理B也是和A一样.
---->也就是说, 同时不能有两个线程访问共享资源, 属于互斥操作.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值