计算机操作系统:linux和C语言

问题遇到的现象和发生背景

计算机操作系统: linux下的c语言

用代码块功能插入代码,请勿粘贴截图

差别仅仅在子进程1写入内容输出时候 加没加\n

img

下面是我的代码


#include 
#include 
#include 
#include 
#include 
#include  
#include 
#define MAX_DATA_LEN 256
#define DELAY_TIME 1
int main()
{
int fd[2];
  pid_t pid1,pid2;
  const char *str1="子进程111";
  const char *str2="子进程222";
  char buf[1024];
  int writeOne,writeTwo,readTotal;
  if (pipe(fd) < 0){
    printf("pipe create error\n");
    exit(1);
  }
  //子进程1
  if((pid1=fork())==0){
    close(fd[0]);
    if(writeOne=write(fd[1],str1,strlen(str1))!=-1){
        printf("写入内容为:%s\n",str1);
        //printf("写入内容为:%s",str1);
    }
   //子进程2
     if((pid2=fork())==0){
   
    if(writeOne=write(fd[1],str2,strlen(str2))!=-1){
        printf("写入内容为:%s\n",str2);
    }
  }
    close(fd[1]);
  }else{
    close(fd[1]);
    sleep(DELAY_TIME);
    if((readTotal=read(fd[0],buf,MAX_DATA_LEN))>0){
        printf("读到内容:%s",buf);
    }
    close(fd[0]);
    exit(0);
  }

}
 

运行结果及报错内容

我不明白为什么输出两次写入内容子进程111

img

fork 执行会调用2次,第一次是 create 产生父进程,有了第一次输出。第二次调用是复制产生子进程,出现第二次输出。fork调用本身的特性。

img


另外通过getpid()和getppid()可以看出过程。

img