/*
*进程1发送消息,进程2接受消息
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
#include </usr/include/bits/pthreadtypes.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
pthread_mutex_t mutex1;
pthread_cond_t cond1;
/pipe
int fd1[2]={0};
FILE* fp;
//thread 1 progress
void pthread1_prc1(void){
char buffer[1024];
char path[50]="/home/dzk/Documents/test_proj/readme.txt";
printf("%s\n",path);
//pipe
char pipebuf1[100]="now we from pipe1\n";
write(fd1[1],pipebuf1,strlen(pipebuf1)); //这里开始写管道fd[1]
strcpy(pipebuf1,"nothing");
close(fd1[1]);
printf("this is pipe in thread1 \n");
pthread_exit(0);
}
//thread 2 progress
void pthread1_prc2(void){
char buffer[1024];
//pipe
char pipebuf2[100]="now we from pipe2\n";
read(fd1[0],pipebuf2,strlen(pipebuf2)); //接受并打印出来
printf("main thrad pipe get from pipe1: %s",pipebuf2);
close(fd1[0]);
pthread_exit(0);
}
int main(){
printf("real uid is %d,real gid is %d!\n",getuid(),getgid());
pid_t pid1, pid2;
pid2=fork();//1个进程
pthread_t thread1, thread2;//创建了2个子线程
pipe(fd1);
char pipebuf[200]="this is pipebuf";
///
if(pid2==0){//进程里面创建2线程,线程之间发消息
printf("thread2 is working!\n");
int thread1_id=pthread_create(&thread1,NULL,(void*)pthread1_prc1,NULL);
int thread2_id=pthread_create(&thread2,NULL,(void*)pthread1_prc2,NULL);
if(thread1_id==-1||thread2_id==-1)
{
perror("thread create error\n");
}
}
main thread4
int ret =0;
while(ret==0)//这里格外注意,waitpid是非阻塞的,用了这个while可以变成阻塞的,或者直接用wait()也行
{
ret=waitpid(pid2,NULL,WNOHANG);
}
if(ret==-1)
{
printf("waitpid is error!\n");
//exit(0);
};
ret=pthread_join(thread1,NULL);
ret=pthread_join(thread2,NULL);
if(ret==-1){
printf("thread join is error!\n");
//exit(0);
}
printf("pid = %d; in father process!\n",getpid());
return 0;
}