#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
int fp1 = open("./demo.txt",O_WRONLY | O_CREAT | O_TRUNC,0664);
if(fp1 == -1)
{
perror("Error open");
return 1;
}
int fp2 = open("./demo.txt",O_RDONLY,0664);
if(fp2 == -1){
perror("Error open");
return 1;
}
int res = fork();
if(res == -1){
perror("Error");
return 1;
}
if(res > 0){
//主线程
printf("父进程:");
char a[30];
scanf("%s",a);
int i = write(fp1,a,sizeof(a));
if(i == -1){
perror("Error wrirte");
}
wait(NULL);
}else{
//子线程
sleep(4);
putchar(10);
while(1){
char b[100];
int j = read(fp2,b,sizeof(b));
if(j<= 0){
//perror("Error read");
break;
}
printf("子进程接收:%s",b);
}
wait(NULL);
}
close(fp1);
close(fp2);
return 0;
}
可能出现子进程抢夺时间片,先出现