1. 创建守护进程的代码,要求写上每一步的注释
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
//创建一个孤儿进程
pid_t pid=fork();
if( pid >0 )
{
exit(0);
}
else if(pid == 0)
{
//创建新的会话
pid_t sid =setsid();
printf("sid=%d\n",sid);
//修改目录
chdir("/");
//修改文件权限掩码
umask(0);
//关闭文件描述符
int i=0;
for(i=0;i<1024;i++)
{
close(i);
}
while(1)
sleep(1);
}
else
{
perror("fork");
return -1;
}
2、 pthread_create函数的代码示例捋清楚
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
//创建一个分支线程
void* callback(void *arg)
{
while(1)
{
printf("this is callback\n");
sleep(1);
}
}
int main(int argc, const char *argv[])
{
pthread_t tid=0;
if(pthread_create(&tid,NULL,callback,NULL)!=0)
{
printf("线程创建失败\n");
return -1;
}
printf("线程创建成功\n");
//一个进程至少有一个线程,此处线程为主线程;
while(1)
{
printf("this is main\n");
sleep(1);
}
return 0;
}
主线程中定义一个局部变量,分支线程中如何接收并打印
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
//创建一个分支线程
void* callback(void *arg)
{
while(1)
{
printf("this is callback\n");
printf("*arg=%d\n",*(int *)arg);
sleep(1);
}
}
int main(int argc, const char *argv[])
{
printf("程序准备运行\n");
int a=520;//定义一个局部变量;
pthread_t tid=0;
if(pthread_create(&tid,NULL,callback,&a)!=0)
{
printf("线程创建失败\n");
return -1;
}
printf("线程创建成功\n");
//主线程
while(1)
{
printf("this is main a=%d\n",a);
sleep(1);
}
return 0;
}
综上:在主线程中创建一个局部变量,分支线程是可以访问;
效果图: