linux系统编程

来源:互联网 发布:sql注入 or 1 1 编辑:程序博客网 时间:2024/06/05 16:54
操作系统的职责
    操作系统用来管理所有的资源,并将不同的设备和不同的程序关联起来。
    linux系统编程:在有操作系统的环境下编程,并使用操作系统提供的系统调用及各种库,对系统资源进行访问。
    系统调用是操作系统提供给用户程序的一组函数接口。
    系统调用按照功能逻辑大致可分为:进程控制、进程间通信、文件系统控制、系统控制、内存管理、网络管理、socket控制、用户管理。
    系统调用的返回值:通常,用一个负数表明错误,返回0值表示成功。
使用系统调用实现cp命令:
    原理:使用系统调用open打开文件,使用read从文件读数据,使用write向文件写数据。
    传给可执行程序的参数个数存放在main函数的argc中,参数首地址存放在指针数组argv中。
    假如你当前目录中已经存在文本文件test.txt.
    编译:gcc cp.c
    执行:./a.out ./test.txt ./mytest.txt

#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <stdlib.h>#include <fcntl.h>#include <unistd.h>int main(int argc, char * argv [ ]){int rdfd = 0;int wrfd = 0;int rdnum = 0;int wrnum = 0;char readbuf[512] = "";if (argc < 3){printf("cmd number is not match!\n");exit(1);}rdfd = open(argv[1],O_RDWR,0666);wrfd = open(argv[2],O_RDWR | O_CREAT,0666);if ((rdfd < 0) || (wrfd < 0))printf("open fail!\n");else{rdnum = read(rdfd,readbuf,24);if (rdnum < 0)printf("read fail!\n");else{wrnum = write(wrfd,readbuf,rdnum);if (wrnum < 0)printf("write fail!\n");}}return 0;}


0 0