64,632
社区成员
发帖
与我相关
我的任务
分享
#include <sys/types.h>/*提供类型pid_t的定义,在PC机上与int类型相同*/
#include <unistd.h>/*提供系统调用的定义*/
void* thread(void* str)
{
str = new char[100];
}
main()
{
pid_t pid;
char *str;
/*此时仅有一个进程*/
printf("PID before fork():%d\n",(int)getpid());
//创建一个线程
ret=pthread_create(&id,NULL,(void *) thread,str); //创建线程传入str作为分配空间用
if(ret!=0){
printf ("Create pthread error!n");
exit (1);
}
pid=fork();
/*此时已经有两个进程在同时运行*/
if(pid <0)
printf("error in fork!");
else if(pid==0) {
//这里是子进程就是一个新的地址空间,复制了主进程的地址空间,可以但是不是
//之前的主线程的了
printf("I am the child process, my process ID is d%\n",getpid());
delete[] str;
}
else {
waitpid();
delete[] str; //如果子进程的str跟主函数共享,那么这里是会运行时错误的
printf("I am the parent process, my process ID is d%\n",getpid());
}
}
char* g_pAddr = 0;
void treadfunc(void* para)
{
g_pAddr = new char[100];
// do other things
}
int main()
{
_beginthread(treadfunc, 0, NULL); // 启动线程
sleep(1000);
//access char[100] through g_pAddr
delete [] g_pAddr;
return 0;
}