linux系统编程

操作系统的职责
    操作系统用来管理所有的资源,并将不同的设备和不同的程序关联起来。
    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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

书灯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值