Bootstrap

IO-进程-多线程编程

1:思维导图

2:创建2个子进程 父进程负责:向文件中写入数据 2个子进程负责:从文件中读取数据 要求:一定保证1号子进程先读取,2号子进程后读取 使用文件IO去实现

 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;
int main(int argc, const char *argv[])
{
	pid_t pid=fork();
	if(pid>0)
	{
		int wfp=open("0.txt",O_WRONLY | O_CREAT | O_TRUNC,0666);
		char ch[50]={"hello world"};
		write(wfp,ch,sizeof(ch));
		close(wfp);
		waitpid(-1,NULL,0);
		pid_t pid2=fork();
		if(pid2>0)
		{
			waitpid(-1,NULL,0);
		}
		else if(pid2==0)
		{
			int rfp2=open("0.txt",O_RDONLY);
			char ch2[50]="";
			read(rfp2,ch2,sizeof(ch2));
			printf("2号子进程:%s\n",ch2);
			close(rfp2);
		}
	}
	else if(pid==0)
	{
		int rfp1=open("0.txt",O_RDONLY);
		char ch1[50]="";
		read(rfp1,ch1,sizeof(ch1));
		printf("1号子进程:%s\n",ch1);
		close(rfp1);
	}
	return 0;
}

3:创建一个线程(1个主线程和一个分支线程)
    主线程负责:输入三角形的三条变长
    分支线程负责:计算三角形的面积(自己百度海伦公式) 海伦公式里面要用到开平方 sqrt函数,使用sqrt函数编译的时候需要在编译的最后加上 -lm
    这里随便怎么整,一定保证先输入数据,再计算面积

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
#include <math.h>

typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;

void Scanf(char const* filename)
{
	printf("请输入三角形的三边长:");
	int a,b,c;
	scanf("%d%d%d",&a,&b,&c);
//	fflush(stdin);
	FILE* wfp=fopen("1.txt","w");
	fprintf(wfp,"%d %d %d",a,b,c);
	fclose(wfp);
}

void computing(char const* filename)
{
	sleep(5);
	int a,b,c;
	float p,area;//p为半周长,area为三角形面积:
	FILE* rfp=fopen("1.txt","r");
	fscanf(rfp,"%d%d%d",&a,&b,&c);
	p=(a+b+c)/2.0;
	area=sqrt(p*(p - a) *(p - b) *(p - c));
	printf("三角形面积为:\n%f\n",area);
	fclose(rfp);
}
void* thread_main(void *arg)
{
	computing("1.txt");
}

int main(int argc, const char *argv[])
{
	pthread_t id;
	pthread_create(&id,0,thread_main,0);
	pthread_detach(id);

	Scanf("1.txt");
	pthread_join(id,NULL);
	return 0;
}
;