守护进程创建

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")
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值