- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
- 4、该文档为VIP文档,如果想要下载,成为VIP会员后,下载免费。
- 5、成为VIP后,下载本文档将扣除1次下载权益。下载后,不支持退款、换文档。如有疑问请联系我们。
- 6、成为VIP后,您将拥有八大权益,权益包括:VIP文档下载权益、阅读免打扰、文档格式转换、高级专利检索、专属身份标志、高级客服、多端互通、版权登记。
- 7、VIP文档为合作方或网友上传,每下载1次, 网站将根据用户上传文档的质量评分、类型等,对文档贡献者给予高额补贴、流量扶持。如果你也想贡献VIP文档。上传文档
查看更多
例题1 程序A生成1个文件,其大小为1000字节,其内容为小写字母abcd...z的循环。试编写该程序。
文件名 t1.c
#include stdio.h
#include stdlib.h
#include fcntl.h
int main()
{
char x;
int i;
int fd=open(aa,O_CREAT|O_TRUNC|O_WRONLY,0666);
if(fd0){printf(open file error!\r\n);exit(0);};
for(i=0;i1000;i++)
{
x=a+(i%26);
write(fd,x,1);
}
close(fd);
}
例题2 读出一个文件a.txt的倒数第2个字节和倒数第1个字节,显示在屏幕上。并且显示出当前时间。
文件名 t2.c
#include stdio.h
#include stdlib.h
#include fcntl.h
#include time.h
int main()
{
char x[2];
int fd=open(a.txt,O_RDONLY);
if(fd0){printf(open file error!\r\n);exit(0);};
lseek(fd,-3,SEEK_END);
read(fd,x,2);
printf(倒数第二和第一字节为%c %c\r\n,x[0],x[1]);
close(fd);
time_t t;
time(t);
printf(当前时间:%s,asctime(localtime(t)));
}
例题3 产生一个进程树 父进程有3个子进程,这三个子进程分别有2个子进程。每个进程退出前打印自己的进程id号
文件名t3.c
#include stdio.h
#include stdlib.h
#include fcntl.h
int main()
{
int ret,i;
for(i=0;i3;i++)
{
ret=fork();
if(ret==0)break;
}
if(ret==0)
for(i=0;i2;i++)
{
ret=fork();
if(ret==0)break;
}
sleep(10);
printf(thread %d is exiting now \r\n,getpid());
}
测试方法:
在另一窗口
#su
#pstree -a
例题4 编写两程序 实现消息队列通信
程序名t4snd.c
#include stdio.h
#include stdlib.h
#include fcntl.h
#include string.h
#include sys/msg.h
#include sys/types.h
#include sys/ipc.h
#include sys/errno.h
struct msgbuf
{
long mtype;
char ctext[100];
};
int main()
{
struct msgbuf buf;
int msid;
msid=msgget(0x1000,0666|IPC_CREAT);
if(msid0){printf(open failed\r\n);exit(0);};
while(1)
{
buf.mtype=getpid();
scanf(%s,buf.ctext);
while((msgsnd(msid,buf,strlen(buf.ctext),0))0)
{
if(errno==EINTR)continue;
return ;
}
if(strcmp(buf.ctext,exit)==0)break;
}
return 0;
}
文件名t4rev.c
#include stdio.h
#include stdlib.h
#include fcntl.h
#include string.h
#include sys/msg.h
#include sys/types.h
#include sys/ipc.h
#include sys/errno.h
struct msgbuf
{
long mtype;
char ctext
文档评论(0)