华清远见上海中心22071班

创建守护进程的代码

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
	//1.创建一个孤儿进程
	pid_t pid=fork();
	if(pid>0)
	{

	}
	else if(0==pid)
	{
		//2.创建新的会话组
		pid_t sid=setsid();
		if(sid<0)
		{
			perror("setsid");
			return -1;
		}
		//3.修改运行目录为不可卸载的文件系统
		chdir("./tmp");
		//注意:从当前位置后,进行运行在"./tmp"下面
		//
		//4.umask请0
		umask(0);
		//关闭所有的文件描述符
		int  i=0;
		for(i=0; i<1024; i++)
		{
			close(i);
		}
		while(1)
		{
			//守护进行的功能代码
			sleep(1);
		}

	}

	else
	{
		perror("fork");
		return -1;
	}


	return 0;
}

pthread_create函数的代码示例

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *callback(void *arg)  		//void *arg = NULL;
{
	while(1)
	{
		printf("p\n");
		printf("这是一个分线程\n");
		sleep(1);
	}
	return NULL;
}
int main(int argc, const char *argv[])
{
	printf("this is main function\n");
	
	pthread_t a;
	int pthread=pthread_create(&a, NULL, callback, NULL);
	if(0!=pthread)
		{
			perror("pthread_create");
			return -1;
		}
	printf("分支线创建成功\n");
	while(1)
	{
		printf("这是一个主线成\n");
		sleep(1);
	}


	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值