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钟获取一次系统时间,并将这个时间写入磁盘文件。

  分析:

  • 每隔2S钟: 使用setitimer函数设置时钟, 该时钟发送的是SIGALRM信号,
  • 信号操作: 注册信号处理函数,signal或者sigaction, 还有一个信号处理函数
  • 获取一次系统时间: time函数的使用, ctime函数的使用
  • 写入磁盘文件: 文件操作函数 —> open write close

mydaemon.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
    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;
}

在这里插入图片描述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;
}
  1. 线程退出: pthread_exit
  2. 回收子线程: pthread_join
//线程退出函数测试
#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;
}
  1. 设置子线程为分离属性: pthread_detach
//设置子线程为分离属性
#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;
}
  1. 杀死(取消)线程: pthread_cancel
//创建子线程
#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;
}
  1. 比较两个线程ID是否相等: pthread_equal
//比较线程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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值