fork()创建子进程
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>
int main(void)
{
pid_t child;
/* 创建子进程 */
if((child=fork())==-1)
{
printf("Fork Error : %s\n", strerror(errno));
exit(1);
}
else
if(child==0) //子进程
{
printf("I am the child: %d\n", getpid());
exit(0);
}
else//父进程
{
printf("I am the father:%d\n",getpid());
return 0;
}
}
fork()创建的子进程后,父子进程是同时、独立运行的,进程的空间是相互独立的,没有固定先后顺序。
jbc@jbc-virtual-machine# 45:~/work/guoqian/code1/2-2-1$ ./fork_pid
I am the child: 3255
I am the father:3254
jbc@jbc-virtual-machine# 46:~/work/guoqian/code1/2-2-1$ ./fork_pid
I am the father:3260
I am the child: 3261
vfork()创建子进程
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>
int main(void)
{
pid_t child;
/* 创建子进程 */
if((child=vfork())==-1)
{
printf("Fork Error : %s\n", strerror(errno));
exit(1);
}
else
if(child==0) // 子进程
{
sleep(1); //子进程睡眠一秒
printf("I am the child: %d\n", getpid());
exit(0);
}
else //父进程
{
printf("I am the father:%d\n",getpid());
exit(0);
}
}
vfork()创建子进程后必定是子进程运行完才会运行父进程。
jbc@jbc-virtual-machine# 55:~/work/guoqian/code1/2-2-2$ ./a.out
I am the child: 3504
I am the father:3503
jbc@jbc-virtual-machine# 56:~/work/guoqian/code1/2-2-2$ ./a.out
I am the child: 3509
I am the father:3508
创建线程
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
struct menber
{
int a;
char *s;
};
/*线程执行函数*/
void *create(void *arg)
{
struct menber *temp;
temp=(struct menber *)arg;
printf("menber->a = %d \n",temp->a);
printf("menber->s = %s \n",temp->s);
return (void *)0;
}
int main(int argc,char *argv[])
{
pthread_t tidp;
int error;
struct menber *b;
/*为结构体指针b分配内存并赋值*/
b=(struct menber *)malloc( sizeof(struct menber) );
b->a = 4;
b->s = "zieckey";
/*创建线程并运行线程执行函数*/
error = pthread_create(&tidp, NULL, create, (void *)b);
if( error )
{
printf("phread is not created...\n");
return -1;
}
sleep(1); //进程睡眠一秒使线程执行完后进程才会结束
printf("pthread is created...\n");
return 0;
}
线程和任务(task)有点类似,使用pthread_create()创建线程后,线程为就绪态,运行结果:
jbc@jbc-virtual-machine# 64:~/work/guoqian/code1/2-5-1$ ./a.out
menber->a = 4
menber->s = zieckey
pthread is created...
线程等待
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
void *thread(void *str)
{
int i;
for (i = 0; i < 3; ++i)
{
sleep(2);
printf( "This in the thread : %d\n" , i );
}
return NULL;
}
int main()
{
pthread_t pth;
int i;
/*创建线程并执行线程执行函数*/
int ret = pthread_create(&pth, NULL, thread, NULL);
printf("The main process will be to run,but will be blocked soon\n");
/*阻塞等待线程退出*/
pthread_join(pth, NULL);
printf("thread was exit\n");
for (i = 0; i < 3; ++i)
{
sleep(1);
printf( "This in the main : %d\n" , i );
}
return 0;
}
pthread_join()将会阻塞当前进程直到线程退出,运行结果:
The main process will be to run,but will be blocked soon
This in the thread : 0
This in the thread : 1
This in the thread : 2
thread was exit
This in the main : 0
This in the main : 1
This in the main : 2