多进程交替控制输出Linux下使⽤两个进程,交替控制输出1-10之间的数
#include<iostream>
using namespace std;
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <stdlib.h>
#include <iostream>
#include <sys/types.h>
#include <string.h>
#include <string>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;
int fd1[2], fd2[2];
void fun1(){
char buf[105];
while(1){
memset(buf, 0, sizeof(buf));
if(read(fd1[0], buf, sizeof(buf)) != -1){
int *a = (int *)buf;
cout << "fun1 = " << *a << endl;
int c = *a + 1;
//将下⼀个要输出的值写⼊⼦进程的缓存区
memset(buf, 0, sizeof(buf));
memcpy(buf, &c, sizeof(int));
write(fd2[1], buf, sizeof(int));
if(c >= 10){  cout << "fun1 end\n";  return;}
}
}
}
void fun2(){
char buf[105];
while(1){
memset(buf, 0, sizeof(buf));
//读管道
if(read(fd2[0], buf, sizeof(buf)) != -1){
int *a = (int *)buf;
//进程输出结束
if(*a > 10){
cout << "fun2 end\n";
return;
}
cout << "fun2 = " << *a << endl;
int c = *a + 1;
//清空缓存区,将下⼀个要输出的值写⼊主进程的缓存区
memset(buf, 0, sizeof(buf));
memcpy(buf, &c, sizeof(int));
write(fd1[1], buf, sizeof(int));
}
}
}
并输出
int main(){
//创建两个管道,主进程和⼦进程之间通过管道通信,
//fd1[0]是⼦进程的读管道, fd1[1]是⼦进程的写管道
/
/fd2[0]是主进程的读管道,fd2[1]是主进程的写管道
pipe(fd1), pipe(fd2);
int a = 0;
//写进程
write(fd1[1], &a, sizeof(int));
//创建⼀个⼦进程
pid_t pid = fork();
//⼦进程输出
if(pid == 0){
fun2();
}else{
/
/主进程输出
fun1();
wait(&pid);
}
return0;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。