Linux操作系统期末练习题lym

printf(\ lseek(fd,0,SEEK_SET); ftruncate(fd,8); num=read(fd,buf2,8); if(num!=8) printf(\ write(1,buf2,8); close(fd); }

4.实现“cat文件名”显示文件内容 #include

main(int argc,char *argv[]) {

int fd; int num; char buf[10]; if(argc!=2) {

printf(\ exit(1); }

fd=open(argv[1],O_RDONLY); if(fd==-1) {

perror(\ exit(1); }

while((num=read(fd,buf,10))!=0) write(1,buf,num); close(fd); }

5.实现“cp 原文件 目标文件” #include #include

main(int argc,char *argv[]) {

int from,to; int num; char buf[10]; if(argc!=3) {

printf(\ exit(1); }

from=open(argv[1],O_RDONLY);

to=open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0644); num=read(from,buf,10); while(num!=0) { write(to,buf,num); num=read(from,buf,10); }

close(from); close(to); }

6.编写程序pro3.c,将字符串“hello world”通过输出重定向方式写入文件f1中 #include #include #include #include #include main() { int fd; if((fd=open(\Y|O_CREAT,0644))==-1) perror(\ if(dup2(fd,1)==-1) perror(\ printf(\ close(fd); }

7.使用fork创建进程,在子进程中打印“I am the child”和子进程pid,在父进程中打印“I am the father”和父进程pid #include #include #include int main() {

pid_t pid; pid = fork(); if(pid < 0) {

perror(\ exit(1); }

else if(pid == 0)

printf(\ else

printf(\ exit(0); }

8.创建子进程,在子进程中执行“ps -A”命令,父进程等待子进程结束后打印“child over” 及所处理的子进程进程号 #include #include main() { pid_t pid,cpid; int i; char* args[64]; args[0]=”ps”; args[1]=”-A”; args[2]=NULL; pid=fork(); if(pid<0) { perror(“fork”); exit(1); } else if(pid==0) { execvp(args[0],args); exit(0); } else { cpid=wait(NULL); printf(“child over! cpid=%d\\n”,cpid); } }

9.编写程序处理SIGINT信号,当程序接收到SIGINT信号后输出“SIGINT is caught” #include #include

void signal_handler(int signum) {

switch(signum) {

case SIGINT:

printf(\ break; } }

int main() {

signal(SIGINT,signal_handler); pause(); return 0; }

10.使用PIPE时限父子进程向子进程发送1234567890,子进程接收并显示 #include #include main() {

int pfd[2]; char buf[32]; pid_t pid; pipe(pfd);

if((pid=fork())<0) perror(\ else if(pid>0) {

close(pfd[0]);

write(pfd[1],\ } else {

close(pfd[1]);

read(pfd[0],buf,11);

printf(\ } }

联系客服:779662525#qq.com(#替换为@)