您的位置:首页 > 运维架构 > Linux

Linux Linux程序练习四

2016-08-28 22:15 246 查看
编写两个不同的可执行程序,名称分别为a和b,b为a的子进程。
在a程序中调用open函数打开a.txt文件。
在b程序不可以调用open或者fopen,只允许调用read函数来实现读取a.txt文件。
(a程序中可以使用 fork与execve函数创建子进程)。


a程序

//fork共享文件标识符
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int arg, char * args[])
{
pid_t child=0;
int status;
child=fork();
if(child==-1)
{
printf("system is game over\n");
return -1;
}
//open the file in read mode
int fd=open("a.txt",O_RDONLY);
if(fd==-1)
{
printf("open the file failed ! \n error msg:%s",strerror(errno));
return -1;
}
if(child==0)
{
char buf[10]={0};
sprintf(buf,"%d",fd);
char * argv[]={"../2/tec",buf,NULL};
execve("../2/tec",argv,NULL);
}else
{
//父进程中关闭文件描述符
close(fd);
printf("i am parent, i am wait!\n");
wait(&status);
printf("child msg is:%d\n",WEXITSTATUS(status));
printf("parent is end!\n");
}
return 0;
}


b程序

//execve共享文件标识符
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int arg, char * args[])
{
if(arg<2)
{
printf("请输入一个参数!\n");
return -1;
}
int fd=atoi(args[1]);
if(fd<3)
{
printf("缺少文件标识符!\n");
return -1;
}
//read the file
char buf[50]={0};
read(fd,buf,sizeof(buf));
printf("the message is:%s\n",buf);
//关闭文件描述符
close(fd);
return 2;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: