⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 管道-两个子进程写父进程读.txt

📁 这是linux下关于进程操作的两个例子,分别是"父子进程都写入文件"和"管道-两个子进程写父进程读".这两个程序对初学都理解linux下的多进程操作很有帮助.在linux GCC下编译通过.
💻 TXT
字号:
/*编写一个程序,建立一个管道,父进程生成子进程X,Y,分别写入管道,父进程读*/
#include<unistd.h>
#include<sys/types.h>
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>
#include<errno.h>
int main(void)
{
static const char mesg1[]="这是子进程#1#写的";
static const char mesg2[]="这是子进#2#写的";
int x,y,fd[2];
char buf[100];
size_t n1,n2,n;
n1=strlen(mesg1);
n2=strlen(mesg2);
n=n1+n2;
pipe(fd);
while((x=fork())==-1);
if(x==0)
{
printf("进入子进程1\n");
  if(write(fd[1],mesg1,n1)!=n1)
      {perror("进程一写");exit(1);}
  else
     {printf("进程一写成功\n");exit(0);}
}
else
{printf("进入父进程了\n");
while((y=fork())==-1);
if(y==0)
{    printf("进入进程2\n");
      if(write(fd[1],mesg2,n2)!=n2)
         {perror("进程二写");exit(1);}
      else
        {printf("进程二写成功\n");exit(0);}
}
else
{
if(read(fd[0],buf,100)!=n)
     {perror("父进程读");exit(1);}
else
   {printf("以下是父进程读的内容:\n");
    buf[n]='\0';
    printf("%s",buf);
    printf("\n");
    close(fd[0]);
    close(fd[1]);
     exit(0);
     }
}
}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -