#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t child_pid;
child_pid = fork();
if(child_pid>0)
{
sleep(60);
}
else
{
exit(0);
}
return 0;
}
很简单一个程序,只说明fork() 返回值如果不等于0,则处于子进程中;否则处于父进程;进程可有pid唯一标示。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<pthread.h>
typedef unsigned long u32;
pthread_t ntid;
void *run(void*);
int main()
{
int err;
err = pthread_create(&ntid,NULL,run,NULL);
/*
int pthread_create(pthread_t *restrict thread,const pthread_attr_t* restrict attr, void* (*start_routine)(void), void* restrict arg);
*/
if(err!=0)
{
printf("Can't create thread: %s!\n",strerror(err));
exit(1);
}
printids("main thread:");
sleep(1);//防止在执行新线程之前,主线程执行完就退出,导致进程结束
return 0;
}
void printids(const char* s)
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x) \n",s,(u32)pid,(u32)tid,(u32)tid);
/*
%s 格式为字符串
%u 格式化为long
%x 格式化为16进制
*/
}
void* run(void* arg)
{
printids("new thread:");
return((void*)0);
}
/*
如果一个进程中的任何线程调用exit() ,_Exit(),_exit()将导致整个进程的终止,
当一个线程收到一个默认为进程终止信号时,将导致整个进程终止.
以下方式终止线程但不会终止进程
同一进程的其他线程调用pthread_cancel()
线程调用pthread_exit()
int pthread_cancel(pthread_t thread);
int pthread_exit(pthread_t thread,void** ptr)
*/
这是关于线程的简单程序,一看就懂,就不多说了。
还有一点,即子进程和父进程各有各得空间和资源,fork()时,子进程会复制父进程的资源。
新线程和原先共享同一地址空间,使用同一资源。