zoukankan      html  css  js  c++  java
  • Linux Linux程序练习四

    编写两个不同的可执行程序,名称分别为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
    ");
            return -1;
        }
        //open the file in read mode
        int fd=open("a.txt",O_RDONLY);
        if(fd==-1)
        {
            printf("open the file failed ! 
     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!
    ");
            wait(&status);
            printf("child msg is:%d
    ",WEXITSTATUS(status));
            printf("parent is end!
    ");
        }
        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("请输入一个参数!
    ");
            return -1;
        }
        int fd=atoi(args[1]);
        if(fd<3)
        {
            printf("缺少文件标识符!
    ");
            return -1;
        }
        //read the file
        char buf[50]={0};
        read(fd,buf,sizeof(buf));
        printf("the message is:%s
    ",buf);
        //关闭文件描述符
        close(fd);
        return 2;
    }

  • 相关阅读:
    RedisCacheTool参考其中的文件读写功能
    eclipse eayExplorer 查看代码的资源管理器打开方式
    有关写代码效率的问题
    Eclipse
    解决pdm打开只显示表名不显示字段的步骤
    绝对定位元素的水平垂直居中
    Maven依赖之Scope
    无提示关闭弹出窗口
    Maven模块与模块间的依赖
    Maven+Hibernate4注解0配置示例
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/5816169.html
Copyright © 2011-2022 走看看