实验1. 创建俩个进程, 让子进程读取一个文件, 父进程等待子进程读完文件后继续执行
相关代码:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
int main ()
{
pid_t pc;
pc = fork();
if (pc < 0)
printf("new error");
else if (pc == 0) {
printf("here in child thread\n");
FILE *fp;
fp=fopen("123.456","w+");
if(fp != NULL){
fprintf(fp, "打开文件成功");
fclose(fp);
} else
printf("打开文件成败");
exit (3);
} else {
wait(&pc);
printf(" here in parent thread\n");
}
return 0;
}
实验2, 线程共享进程中的数据, 在进程中直接引用并输出该数据:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
static int shdata = 4;
void*create(void*arg)
{
printf("new pthread....\n");
printf("shared data =%d \n", shdata);
return (void*)0;
}
int main (int argc, char* argv[])
{
pthread_t tidp;
int error;
error = pthread_create(&tidp, NULL, create, NULL);
if (error != 0)
{
printf("failed to create thread");
return -1;
}
printf("before sleep\n");
sleep(1);
printf("success to create thread\n");
return 0;
}
zheng@zheng-ThinkPad-Edge-E430:~/test/thread$ ./a.out
before sleep
new pthread....
shared data =4
success to create thread
zheng@zheng-ThinkPad-Edge-E430:~/test/thread$