创建守护进程的代码
#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;
}