‘壹’ 编写一个利用管道流,实现线程之间的通信,实现文件传输功能java程序
importjava.io.BufferedReader;
importjava.io.BufferedWriter;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.PipedInputStream;
importjava.io.PipedOutputStream;
importjava.io.PrintWriter;
publicclassDay10A{
privateBufferedReaderbr;//字符效率读取流
privateBufferedWriterbw;//字符效率写出流
privatePipedInputStreampis;//管道读取流
privatePipedOutputStreampos;//管道输出流,
privatebyte[]readBytes;//读取缓冲区
privatebyte[]writeBytes;//写出缓冲区
privateStringpath="C:\Users\Administrator\Desktop";
privateFilefile=null;
privateFileOutputStreamfos=null;
Day10A(){
writeBytes=newbyte[1024];
file=newFile(path,"测试.txt");
try{
if(!file.exists()){
file.createNewFile();
fos=newFileOutputStream(file);
}else{
fos=newFileOutputStream(file,true);
}
br=newBufferedReader(newInputStreamReader(System.in));
bw=newBufferedWriter(newPrintWriter(fos));
pis=newPipedInputStream();
pos=newPipedOutputStream();
pis.connect(pos);
}catch(IOExceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
Day10Ad=newDay10A();
d.readFunction();
d.writerFunction();
}
privatevoidreadFunction(){
newThread(newRunnable(){
publicvoidrun(){
while(true){
try{
for(Stringstr=br.readLine();!str.contentEquals("over");str=br.readLine()){
readBytes=str.getBytes();
pos.write(readBytes);
}
}catch(Exceptione){
}
break;
}
try{
pos.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}).start();
}
privatevoidwriterFunction(){
newThread(newRunnable(){
@Override
publicvoidrun(){
try{
Stringstr="";
for(intlen=pis.read(writeBytes);len!=-1;len=pis.read(writeBytes)){
str=newString(writeBytes,0,len);
bw.write(str+" ");
bw.flush();
}
}catch(Exceptione){
}
}
}).start();
}
}
‘贰’ linux管道实验题
<pre t="code" l="cpp">#include <unistd.h>
#include <stdio.h>
//警告: 该程序未做错误验证, 未关闭管道(由系统自动关闭)
int main()
{
int p2c[2]; // 该管道父进程写,子进程读
int c2p[2]; // 该管道子进程写,父进程读
// 创建2条管道
pipe(p2c);
pipe(c2p);
int pid = fork();
int fd_read, fd_write; // 这两个描述符用于保存某进程读端和写端
int pid_my; // 保存某进程自身的pid
int pid_other; // 另一进程的pid,通过
if ( pid == 0 ) { // 子进程
fd_read = p2c[0];
fd_write= c2p[1];
// 通过getpid取得自身pid,写到管道里
pid_my = getpid();
write(fd_write, pid_my, sizeof(int));
// 从另一管道读取另一进程的pid
read(fd_read, pid_other, sizeof(int));
// 打印读取到的pid
printf("Recive pid : %d\n", pid_other);
} else { // p
fd_read = c2p[0];
fd_write= p2c[1];
pid_my = getpid();
// 由于子进程是先写自身pid,父进程最好先读取子进程的pid
read(fd_read, pid_other, sizeof(int));
write(fd_write, pid_my, sizeof(int));
printf("Recive pid : %d\n", pid_other);
}
return 0;
}
‘叁’ 关于linux系统下管道 通信的问题(高手回答)
不是高烂歼手,没事写了一下b,请大家批评指正:
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/基哗types.h>
int main()
{
int n, fd[2];
pid_t pid, pid1;
char buffer[BUFSIZ+1];
if(pipe(fd) < 0)
{
printf("pipe failed!\n");
exit(1);
}
if((pid = fork()) < 0)
{
printf("fork failed");
exit(1);
}
else if(pid > 0)
{
if((pid1 = fork()) < 0)
{
printf("fork failed");
exit(1);
}
else if(pid1 >0)
{
close(fd[0]);
write(fd[1], "Hello World!", 12);
}
else
{
close(fd[1]);
n = read(fd[0], buffer, 6);
write(STDOUT_FILENO,"\np1 get:\n", 8);
write(STDOUT_FILENO, buffer, n);
}
}
else
{
close(fd[1]);
n = read(fd[0], buffer, 6);
write(STDOUT_FILENO,"搏历行\np0 get:\n", 8);
write(STDOUT_FILENO, buffer, n);
}
exit(0);
}
‘肆’ 编写一个程序实现以下功能: (1)使用fork()创建进程。 (2)使用管道实现子进程和父进程之间的通信。
编写一段程序,使用系统调用fork( )创建两个子进程。当此程序运行时,在系统中有一个父进程和两个子进程活动。让每一个进程在屏幕上显示一个字符;父进程显示字符“a”,子进程分别显示字符“b”和“c”。试观察记录屏幕上的显示结果,并分析原因。
〈程序〉
#include<stdio.h>
main()
{
int p1,p2;
if(p1=fork()) /*子进程创建成功*/
putchar('b');
else
{
if(p2=fork()) /*子进程创建成功*/
putchar('c');
else putchar('a'); /*父进程执行*/
}
}
<运行结果>
bca(有时会出现abc的任意的排列)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
编制一段程序,实现进程的管道通信。使用系统调用pipe()建立一条管道线。两个子进程p1和p2分别向通道个写一句话:
child1 process is sending message!
child2 process is sending message!
而父进程则从管道中读出来自两个进程的信息,显示在屏幕上。
〈程序〉
#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);
sprintf(outpipe,"child 1 process is sending message!");
/*把串放入数组outpipe中*/
write(fd[1],outpipe,50); /*向管道写长为50字节的串*/
sleep(5); /*自我阻塞5秒*/
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(5);
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);
}
}
}
〈运行结果〉
延迟5秒后显示:
child1 process is sending message!
再延迟5秒:
child2 process is sending message!
附:我承认我是复制的 不过很符合题意~
‘伍’ 用C语言编写一个简单的管道通信程序 需用到fock() 在Linux下可以运行
一仔并乱个利用pipe,进行父子进程间通信的小念档例子
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(void)
{
int fds[2];
pid_t pid;
if(pipe(fds) == -1)
{
perror("pipe error");
exit(1);
}
pid=fork();
if(pid == -1)
{
perror("fork error");
exit(1);
}
if(pid == 0)//parent
{
char buf[1024];
int n;
close(fds[1]);
n = read(fds[0], buf, 1024);//从管道读端读出数据到buf
write(STDOUT_FILENO, "child:",6);
write(STDOUT_FILENO, buf, n);//将读到的数据打印到终端
}
else//child
{
close(fds[0]);
write(fds[1], "hello world\蔽掘n", 12);//向管道写端写入数据“hello world\n”
wait(NULL);
}
return 0;
}
‘陆’ c++ 进程间通信(管道和共享内存分别写),给个简单代码,包注释
#include<stdio.h>
#include<windows.h>
intmain(intargc,char*argv[])
{
if(argv[1]==0){//如果是主进程
HANDLEhPipeW,hPipeR;//读管道和写管道
STARTUPINFOAsi;
PROCESS_INFORMATIONpi;
charstr[128];
charparam[1024];
CreatePipe(&hPipeR,&hPipeW,NULL,0);
SetHandleInformation(hPipeW,HANDLE_FLAG_INHERIT,HANDLE_FLAG_INHERIT);//使得子进程可以继承这个句柄
ZeroMemory(&si,sizeof(si));
si.cb=sizeof(si);
sprintf(param,""%s"%x",argv[0],hPipeW);//传给子进程的参数
if(CreateProcessA(argv[0],param,0,0,TRUE,0,0,0,&si,&pi)!=FALSE){
char*pstr=str;
CloseHandle(hPipeW);//关闭管道的输入端,因为此时已经由子进程使用输入端了
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
for(;;){
DWORDr;
ReadFile(hPipeR,pstr,128,&r,0);//从管道读取数据
if(r>0)
pstr+=r;
else
break;
}
CloseHandle(hPipeR);
puts(str);
}
return0;
}else{//如果是子进程
charstr[]="Hello!";
HANDLEhPipeW;
DWORDr;
sscanf(argv[1],"%x",&hPipeW);//从参数获取管道的写句柄
WriteFile(hPipeW,str,sizeof(str),&r,0);//往管道写入数据
CloseHandle(hPipeW);
return0;
}
}#include<stdio.h>
#include<string.h>
#include<windows.h>
intmain(intargc,char*argv[])
{
if(argv[1]==0){//如果是作为主进程运行
HANDLEhShmem;
charparam[1024];
STARTUPINFOAsi;
PROCESS_INFORMATIONpi;
char*pstr;
hShmem=CreateFileMapping(INVALID_HANDLE_VALUE,0,PAGE_READWRITE,0,256,0);//创建共享内存对象
SetHandleInformation(hShmem,HANDLE_FLAG_INHERIT,HANDLE_FLAG_INHERIT);//使得句柄可以继承到子进程
sprintf(param,""%s"%x",argv[0],hShmem);
ZeroMemory(&si,sizeof(si));
si.cb=sizeof(si);
CreateProcessA(argv[0],param,0,0,TRUE,0,0,0,&si,&pi);
WaitForSingleObject(pi.hProcess,INFINITE);//等待子进程运行结束
pstr=(char*)MapViewOfFile(hShmem,FILE_MAP_WRITE,0,0,0);//将共享内存对象中的内存块映射到当前进程
puts(pstr);
UnmapViewOfFile(pstr);
CloseHandle(hShmem);
return0;
}else{//如果是作为子进程运行
HANDLEhShmem;
char*pstr;
sscanf(argv[1],"%x",&hShmem);
pstr=(char*)MapViewOfFile(hShmem,FILE_MAP_WRITE,0,0,0);//将共享内存对象中的对象映射到当前进程
strcpy(pstr,"Hello~!");//往共享内存里写入字符串
UnmapViewOfFile(hShmem);
CloseHandle(hShmem);
return0;
}
}
‘柒’ 利用C语言写一个程序实现两个进程间进行管道通信
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>顷告带
#include <雀芦string.h>
#define N 10
#define MAX 100
int child_read_pipe(int fd)
{
char buf[N];
int n = 0;
while(1)
{
n = read(fd,buf,sizeof(buf));
buf[n] = '\0';
printf("Read %d bytes : %s.\n",n,buf);
if(strncmp(buf,"quit",4) == 0)
break;
}
return 0;
}
int father_write_pipe(int fd)
{
char buf[MAX] = {0};
while(1)
{
printf(">");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1] = '\0';
write(fd,buf,strlen(buf));
usleep(500);
if(strncmp(buf,"quit"友闷,4) == 0)
break;
}
return 0;
}
int main()
{
int pid;
int fd[2];
if(pipe(fd) < 0)
{
perror("Fail to pipe");
exit(EXIT_FAILURE);
}
if((pid = fork()) < 0)
{
perror("Fail to fork");
exit(EXIT_FAILURE);
}else if(pid == 0){
close(fd[1]);
child_read_pipe(fd[0]);
}else{
close(fd[0]);
father_write_pipe(fd[1]);
}
exit(EXIT_SUCCESS);
}