0509_IO4

练习1:

创建一对父子进程: 父进程负责向文件中写入 长方形的长和宽 子进程负责读取文件中的长宽信息后,计算长方形的面积

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <stdlib.h>
 4 #include <sys/types.h>
 5 #include <unistd.h>
 6 #include <sys/stat.h>
 7 #include <fcntl.h>
 8 #include <pthread.h>
 9 #include <semaphore.h>
10 #include <wait.h>
11 #include <signal.h>
12 #include <sys/socket.h>
13 #include <arpa/inet.h>
14 #include <sys/socket.h>
15 #include <sys/ipc.h>
16 #include <sys/sem.h>
17 #include <semaphore.h>
18 #include <sys/msg.h>
19 #include <sys/shm.h>
20 #include <sys/un.h>
21 int main(int argc, const char *argv[])
22 {
23     pid_t rel=fork();
24     if(rel==EOF){
25         perror("fork");
26         return -1;
27     }else if(rel>0){
28         int fd=open("./homework.txt",O_WRONLY|O_CREAT|O_TRUNC,0666);
29         if(fd==EOF){
30             perror("open");
31             return -1;
32         }
33         int a=10;
34         int b=10;
35         if(write(fd,&a,4)==EOF){
36             perror("write");
37             return -1;
38         }if(write(fd,&b,4)==EOF){
39             perror("write");
40             return -1;
41         }
42         close(fd);
43         wait(0);
44     }else if(rel==0){
45         int fd=open("./homework.txt",O_RDONLY);
46         if(fd==EOF){
47             perror("open");
48             return -1;
49         }
50         int a=0;
51         int b=0;
52         if(read(fd,&a,sizeof(int))==EOF){
53             perror("read");
54             return -1;
55         }
56         if(read(fd,&b,sizeof(int))==EOF){
57             perror("read");
58             return -1;                                                                                      
59         }
60         printf("S=%d\n",a*b);
61         close(fd);
62     }
63     
64     return 0;
65 }

思维导图: 

  • 15
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值