1. 程式人生 > 實用技巧 >多程序交替控制輸出

多程序交替控制輸出

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); } return 0; }