c语言亲缘线程通过管道通信一些疑问

 亲缘线程在使用管道时,发现第一次使用管道进行进行通信完全正常(./a.out 1),但当重新运行并使用新管道文件时候出现数据无法读取的问题(./a.out 2)(./a.out 3),甚至出现子线程部分语句并未执行问题,下面程序中会出现子进程perror(write)及以后语句未执行得到问题

  1 #include<sys/types.h>
  2 #include<sys/stat.h>
  3 #include<unistd.h>
  4 #include<fcntl.h>
  5 #include<stdio.h>
  6 #include<string.h>
  7 int main(int argc ,char *argv[]){
  8         umask(0);
  9         mkfifo(argv[1],0777);
 10         int len=0;
 11         int *p=&len;
 12         pid_t pid=fork();
 13         perror("fork");
 14         if(pid==0){
 15                 int fd=open(argv[1],O_WRONLY);
 16                 //perror("open");
 17                 char buff[]={'0'};
 18                 printf("这是子进程!\n");
 19                 printf("请输入要通信的字符:");
 20                 scanf("%s",buff);
 21                 *p=strlen(buff);
 22                 write(fd,buff,strlen(buff));
 23                 perror("write");
 24                 printf("子进程len:%d\n",*p);
 25                 close(fd);
 26                 }
 27 
 28       else{
 29                 int fd=open(argv[1],O_RDONLY);
 30 
 31                 //perror("open");
 32                 sleep(5);
 33                 printf("父进程len:%d\n",*p);
 34                 char buff[20]={0};
 35                 printf("这是父进程!\n");
 36                 read(fd,buff,20);
 37                 perror("read");
 38                 printf("父进程读出:%s\n",buff);
 39                 close(fd);
 40         }
 41         return 0;
 42 }

[root@localhost pid]# ./a.out 1
fork: Success
fork: Success
这是子进程!
请输入要通信的字符:23osd
write: Success
子进程len:5
父进程len:0
这是父进程!
read: Success
父进程读出:23osd
[root@localhost pid]# ./a.out 2
fork: Success
fork: Success
这是子进程!
请输入要通信的字符:sdgksls
父进程len:0
这是父进程!
read: Success
父进程读出:
[root@localhost pid]# ./a.out 3
fork: Success
fork: Success
这是子进程!
请输入要通信的字符:dflhlf'fd
父进程len:0
这是父进程!
read: Success
父进程读出:
[root@localhost pid]# ./a.out 1
fork: File exists
fork: File exists
这是子进程!
请输入要通信的字符:wqla
write: File exists
子进程len:4
父进程len:0
这是父进程!
read: File exists
父进程读出:w
[root@localhost pid]# ./a.out 1
fork: File exists
fork: File exists
这是子进程!
请输入要通信的字符:hdshds
write: File exists
子进程len:6
父进程len:0
这是父进程!
read: File exists
父进程读出:hdshds
[root@localhost pid]# ./a.out 1
fork: File exists
fork: File exists
这是子进程!
请输入要通信的字符:wejhee
write: File exists
子进程len:6
父进程len:0
这是父进程!
read: File exists
父进程读出:wejhee
[root@localhost pid]# ./a.out 1
fork: File exists
fork: File exists
这是子进程!
请输入要通信的字符:ahjk2';
父进程len:0
这是父进程!
read: File exists
父进程读出:
[root@localhost pid]# ./a.out 1
fork: File exists
fork: File exists
这是子进程!
请输入要通信的字符:ajgaka
write: File exists
子进程len:6
父进程len:0
这是父进程!
read: File exists
父进程读出:ajgaka
[root@localhost pid]# 

猜你喜欢

转载自blog.csdn.net/qq_34834846/article/details/86376526