码迷,mamicode.com
首页 > 系统相关 > 详细

Linux Linux程序练习四

时间:2016-08-28 23:45:56      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:

编写两个不同的可执行程序,名称分别为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
    {
        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);
    return 2;
}

 

技术分享

Linux Linux程序练习四

标签:

原文地址:http://www.cnblogs.com/zhanggaofeng/p/5816169.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!