/**************************************************
该程序实现的是经过系统调用fork之后,父进程和子进程对
文件的共享存取。该程序有两个参数,一个是已经有的文件名,
另外一个是要创建的新文件名。该进程打开已有的文件,创建
一个新文件。进程调用fork来创建一个子进程。子进程可以通
过使用相同的文件描述符而继承地存取父进程的文件(即父进
程已经打开和创建的文件)。父进程和子进程分别独立地调用
rdwrt函数执行一个循环,实现从源文件中读一个字节,然后
写一个字节到目标文件中区。当系统调用read遇见文件尾时,
函数rdwrt立即返回。
**********************************************************/
#include<fcntl.h>
int fdrd,fdwt;
char c;
rdwrt( )
{
for( ; ; ){
if(read(fdrd,&c,1)!=1) return;
write(fdwt,&c,1);
}
}
main(int argc,char *argv[])
{
if(argc!=3){
exit(1);
}
if((fdrd=open(argv[1],O_RDONLY))==-1)
{
exit(1);
}
if((fdwt=creat(argv[2],0666))==-1)
{
exit(1);
}
fork( );
rdwrt( ); //两个进程执行同样的代码
exit(0);
}
//进程之间的管道通信
#include<string.h>
char string[]="Hello,world";
main()
{
int count,i;
int to_par[2],to_chil[2]; //到父、子进程的管道
char buf[256];
//两次执行系统调用pipe分别在数组to_par和to_chil中分配了两个文件描述符。
pipe(to_par);
pipe(to_chil);
if(fork()==0) //子进程在此执行,子进程从父进程继承了文件描述符0和1。
{
close(0); //关闭老的标准输入
dup(to_child[0]); //将管道的读复制到标准输入
close(1); //关闭老的标准输出
dup(to_par[1]); //将管道的写复制到标准输出
close(to_par[1]); //关闭不必要的管道描述符
close(to_chil[0]); close(to_par[0]); close(to_chil[1]);
for(;;)
{
if((count=read(0,buf,sizeof(buf))==0)
exit();
write(1,buf,count);
}
}
//父进程在此执行
close(1); //重新设置标准输入、输出
dup(to_chil[1]);
close(0);
dup(to_par[0]);
close(to_chil[1]); close(to_par[0]);
close(to_chil[0]); close(to_par[1]);
for(i=0;i<15;i++)
{
write(1,string,strlen(string));
read(0,buf,sizeof(buf));
}
}
//多进程的管道通信
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
int pid1,pid2;
main( )
{
int fd[2];
char outpipe[100],inpipe[100];
pipe(fd); /*创建一个管道*/
while ((pid1=fork( )) == -1);
if(pid1 == 0)
{
lockf(fd[1],1,0);
/*把输出串放入数组outpipe中*/
sprintf(outpipe,"child 1 process is sending message!");
write(fd[1],outpipe,50); /*向管道写长为50字节的串*/
sleep(3); /*自我阻塞3秒*/
lockf(fd[1],0,0);
exit(0);
}
else
{
while((pid2=fork( ))= =-1);
if(pid2= =0)
{
lockf(fd[1],1,0); /*互斥*/
sprintf(outpipe,"child 2 process is sending message!");
write(fd[1],outpipe,50);
sleep(3);
lockf(fd[1],0,0);
exit(0);
}
else
{
wait(0); /*同步*/
read(fd[0],inpipe,50); /*从管道中读长为50字节的串*/
printf("%s\n",inpipe);
wait(0);
read(fd[0],inpipe,50);
printf("%s\n",inpipe);
exit(0);
}
}
}
//多进程的管道通信
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
int pid1,pid2;
main( )
{
int fd[2];
char outpipe[100],inpipe[100];
pipe(fd); /*创建一个管道*/
while ((pid1=fork( )) == -1);
if(pid1 == 0)
{ lockf(fd[1],1,0);
/*把输出串放入数组outpipe中*/
sprintf(outpipe,"child 1 process is sending message!");
write(fd[1],outpipe,50); /*向管道写长为50字节的串*/
sleep(3); /*自我阻塞3秒*/
lockf(fd[1],0,0);
exit(0);
}
else
{
while((pid2=fork( ))= =-1);
if(pid2= =0)
{ lockf(fd[1],1,0); /*互斥*/
sprintf(outpipe,"child 2 process is sending message!");
write(fd[1],outpipe,50);
sleep(3);
lockf(fd[1],0,0);
exit(0);
}
else
{ wait(0); /*同步*/
read(fd[0],inpipe,50); /*从管道中读长为50字节的串*/
printf("%s\n",inpipe);
wait(0);
read(fd[0],inpipe,50);
printf("%s\n",inpipe);
exit(0);
}
}
}